Advertisement
Guest User

Untitled

a guest
Aug 17th, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. /**
  2. * This program creates a new process and provides a simple pipe to
  3. * allow the child to communicate with the parent
  4. * Version 1 -- explicitly using pipe and byte-oriented read/write
  5. * type 'quit' to exit program
  6. */
  7.  
  8. #include <sys/types.h>
  9. #include <unistd.h>
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <string.h>
  13.  
  14. // Maximum number of letters to be communicated
  15. #define MAX 40
  16.  
  17. int main() {
  18. // File descriptor array for the pipe
  19. // * fd[0] will be the end you can read from
  20. // * fd[1] will be the end you can write to
  21. int fd[2];
  22.  
  23. // Character array (string) for reading
  24. char line[MAX];
  25. char input[MAX];
  26.  
  27. pid_t pid;
  28.  
  29. // Create a pipe and check for errors
  30. if(pipe(fd) == -1) {
  31. perror("pipe error");
  32. exit(EXIT_FAILURE);
  33. }
  34.  
  35. // Fork a child process and check for errors
  36. pid = fork();
  37. if(pid == -1) {
  38. perror("error in fork");
  39. exit(EXIT_FAILURE);
  40. }
  41.  
  42. if(pid == 0) {
  43. // Processing for the child process only
  44. printf("The child process is active.\n");
  45.  
  46. // Close the writable end of the pipe, leaving the readable end open
  47. close(fd[0]);
  48.  
  49. // Write a string to the pipe and indicate its length (in bytes)
  50.  
  51. do {
  52. scanf("%s", input);
  53. write(fd[1], input, 26);
  54. } while (strcmp(line, "quit") != 0);
  55.  
  56. } else {
  57. // Processing for the parent process only
  58. printf("The parent process is active.\n");
  59.  
  60. // Close the readable end of the pipe, leaving the writable end open
  61. close(fd[1]);
  62.  
  63. // Read from the pipe
  64. do
  65. {
  66. read(fd[0], line, MAX);
  67. printf("recieved %s\n", line);
  68. } while (strcmp(line, "quit") != 0);
  69. }
  70.  
  71. exit(EXIT_SUCCESS);
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement