Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
execvp之后如何在子进程中使用文件描述符?_C_Linux_Pipe_Fork_Execvp - Fatal编程技术网

execvp之后如何在子进程中使用文件描述符?

execvp之后如何在子进程中使用文件描述符?,c,linux,pipe,fork,execvp,C,Linux,Pipe,Fork,Execvp,我试图使用fork打开一个子进程,然后执行到另一个程序中。 我还希望父进程和子进程使用管道相互通信 以下是父进程- int pipefds[2]; pipe(pipefds); // In original code I check for errors... int readerfd = pipefds[0]; int writerfd = pipefds[1]; if(pid == 0){ // Child close(readerfd); execvp("

我试图使用fork打开一个子进程,然后执行到另一个程序中。 我还希望父进程和子进程使用管道相互通信

以下是父进程-

int pipefds[2];
pipe(pipefds); // In original code I check for errors...
int readerfd = pipefds[0];
int writerfd = pipefds[1];

if(pid == 0){
    // Child
    close(readerfd);
        execvp("./proc2",NULL);
}


在程序“proc2”中,我试图通过以下方式访问writerfd-

write(writerfd, msg, msg_len);

但是,我得到了一个编译时间错误- 错误:“writerfd”未声明此函数中的首次使用

为什么呢?我在这里读到关于堆栈溢出的消息,打开的文件描述符在调用exec时被保留。如果是这样的话,我就不能联系writerfd吗

在使用execvp之后,如何在子进程上写入该文件描述符?做这件事的正确方法是什么?我在哪里可以看到我看了但没有找到的答案


谢谢

调用exec函数时,会保留打开的文件描述符。不保留的是用于存储它们的任何变量的名称

您需要将文件描述符复制到其他程序可以引用的已知文件描述符编号。由于子进程正在写入,您应该将管道的子端复制到文件描述符1,即标准输出:

int pipefds[2];
pipe(pipefds);
int readerfd = pipefds[0];
int writerfd = pipefds[1];

if(pid == 0){
    // Child
        close(readerfd);
        dup2(writerfd, 1);
        execvp("./proc2",NULL);
}
然后proc2可以写入文件描述符1:

write(1, msg, msg_len);
或者,如果消息是字符串,只需使用printf


我在这里读到关于堆栈溢出的消息,打开的文件描述符在调用exec时被保留。这是真的,但这并不意味着您的变量writerfp神奇地出现在一个完全无关的程序中。最简单的方法是将句柄复制到stdout。明白了,谢谢!我还将在手册页中阅读有关dup的内容。再次感谢:-
printf("%s", msg);
fflush(stdout);