写入子进程的文件描述符 [英] Writing to child process file descriptor

查看:156
本文介绍了写入子进程的文件描述符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个节目样本,这既需要从标准和非标准的文件描述符(3或4),如下图所示。

I have a program "Sample" which takes input both from stdin and a non-standard file descriptor (3 or 4) as shown below

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

现在我有另一个程序操作员,它使用execv在子进程中执行上述程序(样本)。现在,我想是通过经营者。

Now i have another program "Operator" which executes the above program(Sample) in a child process using execv. Now what i want is to send input to "Sample" through the "Operator" .

推荐答案

分叉子进程后,但之前调用的execve ,你必须调用 dup2(2)子进程标准输入描述重定向到管道的读端。下面是一个简单的一块code的没有太多的错误检查:

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

这你写从父进程第一管方式都将通过描述符传递到子进程 0 标准输入),以及一切你从第二个管写将交付给描述符 4 以及

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.

这篇关于写入子进程的文件描述符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆