Advertisement
Guest User

Untitled

a guest
Sep 17th, 2014
251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.69 KB | None | 0 0
  1. #include <errno.h>
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #include <stdlib.h>
  5. #include <sys/types.h>
  6. #define bufsize 20
  7.  
  8. int fildes[2];
  9. char buffer[bufsize];
  10. void error(void)
  11. {
  12.  printf("unable to create a new process - job terminated \n");
  13.  fflush(stdout);
  14. }
  15. void child(void)
  16. {
  17.  int pm, i;
  18.  printf("child starts working.\n");
  19.  close(fildes[1]);
  20.  for (i = 0; i<5; i++)
  21.  {
  22.  printf("in child i = %d \n", i);
  23.  pm = read(fildes[0],&buffer,20);
  24.  printf ("child received %d chars from parent\n",pm);
  25.  printf ("message received is: %s ",buffer);
  26.  fflush(stdout);
  27.  sleep(1);
  28.  }
  29.  exit(0);
  30. }
  31. void parent(void)
  32. {
  33.  int i, pm;
  34.  printf("parent starts working.\n");
  35.  close(fildes[0]);
  36.  for (i = 0; i < 5 ; i++)
  37.  {
  38.  switch(i){
  39.  case 0:
  40.     pm = write(fildes[1], "first message \n", 20);
  41.  printf("characters written by parent = %d \n", pm);
  42.     fflush(stdout);
  43.  break;
  44. case 1:
  45.     pm = write(fildes[1], "second message \n", 20);
  46.     printf("characters written by parent = %d \n", pm);
  47.     fflush(stdout);
  48.  break;
  49.  case 2:
  50.     pm = write(fildes[1], "third message \n", 20);
  51.     printf("characters written by parent = %d \n", pm);
  52.     fflush(stdout);
  53.  break;
  54. case 3:
  55.     pm = write(fildes[1], "fourth message \n", 20);
  56.     printf("characters written by parent = %d \n", pm);
  57.     fflush(stdout);
  58. break;
  59. case 4:
  60.     pm = write(fildes[1], "fifth message \n", 20);
  61.     printf("characters written by parent = %d \n", pm);
  62.     fflush(stdout);
  63.  }
  64.  }
  65.  wait(NULL);
  66.  printf("parent terminating\n");
  67.  exit(0);
  68. }
  69. int main(void)
  70. {
  71.  int pp, pid;
  72.  
  73.  pp = pipe (fildes);
  74.  printf("pipe opened with pp = %d \n", pp);
  75.  fflush(stdout);
  76.  pid = fork();
  77.  if (pid == 0)
  78.  child();
  79.  else if (pid == -1)
  80.  error();
  81.  else parent();
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement