Writing to child process file descriptor

孤人 提交于 2019-12-18 13:36:27

问题


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("%s","\nEnter input for stdin");
read(0, pO, 5);    
printf("\nEnter input for fds 3");
read(pfds[0], pX, 5);

printf("\nOutput stout");
write(1, pO, strlen(pO));    
printf("\nOutput fd 4");
write(pfds[1], pX, strlen(pX));

Now i have another program "Operator" which executes the above program(Sample) in a child process using execv. Now what i want is to send input to "Sample" through the "Operator" .


回答1:


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.



来源:https://stackoverflow.com/questions/5953386/writing-to-child-process-file-descriptor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!