写入子进程文件描述符

时间:2011-05-10 16:38:22

标签: c file-descriptor child-process

我有一个程序“Sample”,它从stdin和非标准文件描述符(3或4)中获取输入,如下所示

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));

现在我有另一个程序“Operator”,它使用execv在子进程中执行上述程序(Sample)。现在我想要的是通过“操作员”向“Sample”发送输入。

1 个答案:

答案 0 :(得分:7)

在分配子进程之后,但在调用execve之前,您必须调用dup2(2)将子进程'stdin描述符重定向到管道的读取端。这是一段简单的代码,没有太多的错误检查:

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;
}

这样,您从父进程写入第一个管道的所有内容都将通过描述符0stdin)传递给子进程,并且您从第二个管道写入的所有内容都将被传递到描述符4