Advertisement
Guest User

Untitled

a guest
Jan 24th, 2017
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. //
  2. // CPE334
  3. // PROBLEM SESSION 1: Process Creation & Pipes
  4. // Created by Warat Kaweepornpoj on 1/24/2560 BE.
  5. // 57070501038
  6. //
  7.  
  8. #include <stdio.h>
  9. #include <unistd.h>
  10. #include <sys/types.h>
  11. #include <string.h>
  12.  
  13. int main(int argc, const char * argv[]) {
  14.  
  15. int fd[2];
  16. pid_t child_pid, pid;
  17. char send[30], recv[30];
  18.  
  19. pipe(fd);
  20. child_pid = fork();
  21. pid = getpid();
  22.  
  23. // Problem 1 - Hello from Child
  24.  
  25. if(child_pid==0){
  26. printf("Parent %d\n", pid);
  27. read(fd[0], &recv, sizeof(recv));
  28. printf("%s\n", recv);
  29.  
  30. } else {
  31. sprintf(send, "Hello from %d", pid);
  32. write(fd[1], &send, strlen(send)+1);
  33. printf("Child %d\n", pid);
  34. }
  35.  
  36. close(fd[0]);
  37. close(fd[1]);
  38.  
  39.  
  40. // Problem 2 - Hello from Parent
  41.  
  42. if(child_pid==0){
  43. printf("Parent %d\n", pid);
  44. sprintf(send, "Hello from %d", pid);
  45. write(fd[1], &send, strlen(send)+1);
  46.  
  47. } else {
  48. printf("Child %d\n", pid);
  49. read(fd[0], &recv, sizeof(recv));
  50. printf("%s\n", recv);
  51. }
  52.  
  53. close(fd[0]);
  54. close(fd[1]);
  55.  
  56. return 0;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement