Writing to child process file descriptor

前端 未结 1 1560
野性不改
野性不改 2021-01-01 06:09

I have a program \"Sample\" which takes input both from stdin and a non-standard file descriptor (3 or 4) as shown below

int pfds[2];
pipe(pfds);    
printf(         


        
相关标签:
1条回答
  • 2021-01-01 06:35

    After forking the child process, but before calling execve, you'll have to call dup2(2) to redirect the child process' stdin descriptor to the read end of your pipe. Here is a simple piece of code without much error checking:

    pipe(pfds_1); /* first pair of pipe descriptors */
    pipe(pfds_2); /* second pair of pipe descriptors */
    
    switch (fork()) {
      case 0: /* child */
        /* close write ends of both pipes */
        close(pfds_1[1]);
        close(pfds_2[1]);
    
        /* redirect stdin to read end of first pipe, 4 to read end of second pipe */
        dup2(pfds_1[0], 0);
        dup2(pfds_2[0], 4);
    
        /* the original read ends of the pipes are not needed anymore */
        close(pfds_1[0]);
        close(pfds_2[0]);
    
        execve(...);
        break;
    
      case -1:
        /* could not fork child */
        break;
    
      default: /* parent */
        /* close read ends of both pipes */
        close(pfds_1[0]);
        close(pfds_2[0]);
    
        /* write to first pipe (delivers to stdin in the child) */
        write(pfds_1[1], ...);
        /* write to second pipe (delivers to 4 in the child) */
        write(pfds_2[1], ...);
        break;
    }
    

    This way everything you write to the first pipe from the parent process will be delivered to the child process via descriptor 0 (stdin), and everything you write from the second pipe will be delivered to descriptor 4 as well.

    0 讨论(0)
提交回复
热议问题