4

我有一个程序“Sample”,它同时从标准输入和非标准文件描述符(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 在子​​进程中执行上述程序(示例)。现在我想要的是通过“Operator”将输入发送到“Sample”。

4

1 回答 1

7

在 fork 子进程之后,但在调用之前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;
}

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

于 2011-05-10T18:00:10.393 回答