Advertisement
Guest User

filedescriptorpass

a guest
Sep 7th, 2011
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.33 KB | None | 0 0
  1. /* test.c */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #include <sys/wait.h>
  6.  
  7. int main()
  8. {
  9.     pid_t child;
  10.     int status;
  11.     int pfd[2];
  12.     if (pipe(pfd) != -1)
  13.     {
  14.         char pipe_readend[12]; /* put file descriptor into c-string to be passed */
  15.         sprintf(pipe_readend, "%i", pfd[0]);
  16.         char * arg[2] = {pipe_readend, NULL};
  17.         char message[2] = {'h', 'i'};
  18.         switch(child=fork())
  19.         {
  20.             case -1:
  21.                 printf("Error with fork");
  22.                 break;
  23.             case 0:
  24.             /* child actions */
  25.                 close(pfd[1]); /* close write end */
  26.                 execve("test2", arg, NULL); /* start new process */
  27.                 break;
  28.             default:
  29.             /* parent actions */
  30.                 close(pfd[0]); /* close read end */
  31.                 write(pfd[1], message, 2);
  32.                 close(pfd[1]); /* close write end */
  33.                 waitpid(child, &status, 0); /* wait for child to exit */
  34.                 break;
  35.         }
  36.     }
  37.     return 0;
  38. }
  39. /* test2.c */
  40. #include <stdio.h>
  41. #include <stdlib.h>
  42. #include <unistd.h>
  43.  
  44. int main(int argc, char * argv[])
  45. {
  46.     int read_end = atoi(argv[0]);
  47.     char message[2];
  48.     read(read_end, message, 2);
  49.     printf("%s", message);
  50.     close(read_end);
  51.     return 0;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement