Writing to child process file descriptor

蓝咒 提交于 2019-11-30 10:27:31

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.

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