向子进程文件描述符写入数据

4

我有一个程序"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)。现在我想通过“Operator”向“Sample”发送输入。

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中。


我应该如何将子进程的另一个文件描述符重定向到读取端? - mukesh
@scholar:您可以使用pipe系统调用创建第二组管道,并执行dup2(pfds_2[0], 4)。从父进程的pfds_2[1]写入将传递到子进程的文件描述符4 - Blagovest Buyukliev
我可以向标准输入的文件描述符写入内容,但如何向“Sample”程序的另一个文件描述符写入内容呢? - mukesh
1
所以,您现在已经实现了popen(3)。 - Mel
@Mel:几乎正确,但你不能让popen写入除了stdin以外的任何东西。 - Blagovest Buyukliev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接