fork(1) download
  1. // CS22B1067 Skanda S Bhat
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #include<unistd.h>
  5. #include<sys/wait.h>
  6.  
  7. int main()
  8. {
  9. int pipe_fd[2];
  10. char buffer[100];
  11.  
  12.  
  13. if (pipe(pipe_fd) == -1) {
  14. perror("Pipe creation failed");
  15. return 1;
  16. }
  17.  
  18. int pid = fork();
  19. if (pid < 0) {
  20. perror("Fork failed");
  21. return 1;
  22. }
  23.  
  24.  
  25. if (pid > 0) {
  26. close(pipe_fd[0]);
  27.  
  28.  
  29. printf("Parent: Enter a message to send to the child: ");
  30. fgets(buffer, sizeof(buffer), stdin);
  31.  
  32.  
  33. write(pipe_fd[1], buffer, sizeof(buffer));
  34. printf("Parent: Message sent to child.\n");
  35.  
  36. close(pipe_fd[1]);
  37.  
  38. wait(NULL);
  39. printf("Parent: Child process finished.\n");
  40. }
  41.  
  42. else {
  43. close(pipe_fd[1]);
  44.  
  45.  
  46. read(pipe_fd[0], buffer, sizeof(buffer));
  47. printf("Child: Message received from parent: %s", buffer);
  48.  
  49. close(pipe_fd[0]);
  50. printf("Child: Exiting.\n");
  51. }
  52.  
  53. return 0;
  54. }
  55.  
  56.  
  57.  
Success #stdin #stdout 0s 5268KB
stdin
Standard input is empty
stdout
Child: Message received from parent: Child: Exiting.
Parent: Enter a message to send to the child: Parent: Message sent to child.
Parent: Child process finished.