简体   繁体   English

管道标准输出到其他程序标准输入失败; 没有消息通过管道

[英]piping stdout into other program stdin fails; no message go through the pipe

I'm trying to program a shell with a fork and a pipe in C. I've tried to fork my process into to 2 and make the son speak with its parent: stdout to be the stdin of the child.我正在尝试用 C 语言编写一个带有叉子和管道的 shell。我试图将我的进程分叉到 2 并让儿子与其父对话:stdout 成为孩子的 stdin。 I thought implementing it via a pipe.我想通过管道实现它。 Here is my try:这是我的尝试:

void split(){

int fork_id = fork();

int pipes[2];
 pipe(pipes);

if (fork_id) {
    //parent

   dup2(pipes[1], STDOUT_FILENO);
    close(pipes[0]);
    close(pipes[1]);
} else {
    //child


     dup2(pipes[0], STDIN_FILENO);
    close(pipes[0]);
    close(pipes[1]);
}
}

Afterwards I run software with execvp (they run with the right argv [ I checked it])/ Unfortunately the 2nd program doesn't get the output of the first, it seems to be that it gets "".之后我用 execvp 运行软件(他们用正确的 argv 运行 [我检查过])/不幸的是,第二个程序没有得到第一个的输出,似乎它得到了“”。 Can anyone spot the mistake?任何人都可以发现错误吗?

credit to @kalyum.归功于@kalyum。 I forked before creating the pipe, therefore each process had its own pipe.我在创建管道之前分叉了,因此每个进程都有自己的管道。 therefore no connection was established between the 2.因此2之间没有建立连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM