如何解决关闭管道不会将 EOF 发送到另一端
我想从 C 程序运行外部命令。假设,作为最小的工作示例,我想运行“cat”命令。我使用 fork() 和 execl() 来生成新进程,并通过管道与它通信。
这就是我的问题所在。在终端中,我会通过按 CTRL-D 告诉“cat”我已完成输入。在这里,我试图通过关闭文件描述符来做到这一点——请参阅下面代码中带有 close(outpipefd[1]) 的行——但这似乎不起作用。我的代码停止,因为“猫”正在等待更多输入。
我的代码如下...我做错了什么?提前致谢!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>
int main(void)
{
pid_t pid=0;
int inpipefd[2];
int outpipefd[2];
/*
We create the pipes for communicating with the child process
*/
pipe(inpipefd);
pipe(outpipefd);
if((pid=fork())==0)
{
/*
Child
*/
dup2(outpipefd[0],STDIN_FILENO);
dup2(inpipefd[1],STDOUT_FILENO);
dup2(inpipefd[1],STDERR_FILENO);
/*
We spawn the process
*/
execl("/bin/cat","cat",(char *)(NULL));
/*
Nothing below this line should be executed by child process.
If so,it means that the execl function wasn't successfull,so lets exit!
*/
exit(1);
}
/*
Parent.
Close unused pipe ends.
*/
close(outpipefd[0]);
close(inpipefd[1]);
/*
Now we can write to outpipefd[1] and read from inpipefd[0]
*/
char *greeting="Hello world!\n";
write(outpipefd[1],greeting,strlen(greeting));
/*
Here I believe that closing the pipe should be equivalent to
pressing CTRL-D in a terminal,therefore terminating the cat command...
This is unfortunately not the case!
*/
close(outpipefd[1]);
while(1)
{
char buf[256];
for(int c=0;c<256;c++)
buf[c]=0;
if(read(inpipefd[0],buf,256)<=0)
break;
printf("OUTPUT: %s\n",buf);
}
/*
Send SIGKILL signal to the child process
*/
int status;
kill(pid,SIGKILL);
waitpid(pid,&status,0);
return 0;
}
解决方法
孩子仍然打开了两个管道的两端,因为您从未关闭其中的任何 FD。直到每个引用管道写端的 FD 关闭,它才会返回 EOF。
,您还必须关闭孩子中未使用的管道末端,否则仍有打开的东西阻塞另一端。关闭您在父和子中不使用的内容,您将获得 EOF。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。