Linux 中的 fork、execlp
#include <unistd.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
int f1[2], f2[2];
char buff;
if(pipe(f1) != -1);
printf("Pipe1 allright! \n");
if(pipe(f2) != -1);
printf("Pipe2 allright \n");
if(fork()==0)
{
close(1);
dup(f1[1]);
close(0);
execlp("ls", "ls", "-l", NULL);
}
else
{
if(fork()==0)
{
close(0);
dup(f1[0]);
close(1);
dup(f2[1]);
execlp("grep", "grep", "^d", NULL);
}
else
{
if(fork()==0)
{
close(0);
dup(f2[0]);
execlp("wc", "wc", "-l", NULL);
}
}
}
return 0;
}
我正在尝试执行 ls -l | grep ^d | C 中的 wc -l 。
我尝试了一切...
出了什么问题? :(
输出:Pipe1 好吧!,Pipe2 好吧!
Ps。您的帖子没有太多上下文来解释代码部分;请更清楚地解释您的场景。
#include <unistd.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
int f1[2], f2[2];
char buff;
if(pipe(f1) != -1);
printf("Pipe1 allright! \n");
if(pipe(f2) != -1);
printf("Pipe2 allright \n");
if(fork()==0)
{
close(1);
dup(f1[1]);
close(0);
execlp("ls", "ls", "-l", NULL);
}
else
{
if(fork()==0)
{
close(0);
dup(f1[0]);
close(1);
dup(f2[1]);
execlp("grep", "grep", "^d", NULL);
}
else
{
if(fork()==0)
{
close(0);
dup(f2[0]);
execlp("wc", "wc", "-l", NULL);
}
}
}
return 0;
}
I am trying to do ls -l | grep ^d | wc -l in C.
I tried everythig...
What is wrong? :(
Output: Pipe1 allright!, Pipe2 allright!
Ps. Your post does not have much context to explain the code sections; please explain your scenario more clearly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码存在几个问题:
我认为这应该是真正的错误检查,因此请删除
if
行中的;
。之后运行您的程序,您会注意到
grep
和wc
命令仍然存在,它们不会终止。使用ps(1)
命令检查这一点。ls
命令似乎已终止。假设,四个进程的 pid 是:
查看
/proc/9002/fd
你会看到,文件句柄 0 (stdin
) 仍然开放供阅读:环顾四周,谁还拥有这个句柄,
您会发现,该管道的许多句柄都已打开:
grep
和wc
中的两个都已打开。其他管道句柄也是如此。解决方案:
您必须在
dup
之后严格关闭管道句柄。看这里:There are several problems with your code:
I assume this should be a real error check, so please remove the
;
in theif
line.Running your program after that you will notice, that the
grep
andwc
commands are still there, they don't terminate. Check this with theps(1)
command. Thels
command seems to have terminated.Let's assume, the pids of the four processes are :
Looking into
/proc/9002/fd
you will see, that filehandle 0 (stdin
) is still open for reading:And looking around, who has this handle still open with
you will see, that many handles to this pipe are open: both
grep
andwc
have two of them open. Same is true for the other pipe handles.Solution:
You have to close the pipe handles after
dup
rigorously. Look here:您可能想使用 dup2 而不是 dup,也就是说,对于其他情况,而不是
do
等等
you probably want to use dup2 instead of dup, that is, instead of
do
and so on for other occurencies