【问题标题】:Writing to child process file descriptor写入子进程文件描述符
【发布时间】:2011-05-11 03:03:00
【问题描述】:

我有一个程序“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”。

【问题讨论】:

    标签: c file-descriptor child-process


    【解决方案1】:

    在 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也是。

    【讨论】:

    • 以及如何将子进程的其他文件描述符重定向到读取端
    • @scholar:您可以使用pipe 系统调用创建第二对管道,也可以使用dup2(pfds_2[0], 4)。来自父级的pfds_2[1] 写入将传递到子级中的文件描述符4。
    • 这样我可以写入标准输入的文件描述符,但我如何写入“示例”程序的其他文件描述符。
    • 嗯,你现在已经实现了 popen(3)。
    • @Mel:差不多,但你不能告诉popen 写信给除stdin 之外的任何东西。
    猜你喜欢
    • 2019-06-20
    • 1970-01-01
    • 2012-04-29
    • 1970-01-01
    • 2019-10-11
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    相关资源
    最近更新 更多