使用 C..(使用叉子)实施管道(“|”)
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main(int argc,char **argv)
{
int fd[2];
pid_t childpid;
pipe(fd);
childpid=fork();
if (childpid == -1)
{
perror("Error forking...");
exit(1);
}
if (childpid) /*parent proces*/ //grep .c
{
wait(&childpid); //waits till the child send output to pipe
close(fd[1]);
close(0); //stdin closed
dup2(fd[0],0);
execlp(argv[2],argv[2],argv[3],NULL);
}
if (childpid==0) //ls
{
close(fd[0]); /*Closes read side of pipe*/
close(1); //STDOUT closed
dup2(fd[1],1);
execl(argv[1],NULL);
}
return 0;
}
如果我将命令行参数指定为“ls grep .c”,我应该显示所有“.c”文件。
伪代码:- 我的子进程将运行“ls”&父进程将运行“grep .c”.. 父进程等待子进程完成,以便子进程写入管道。
测试运行:-
bash-3.1$ ls | grep .c
1.c
hello.c
bash-3.1$ ./a.out ls grep .c
bash-3.1$
为什么会发生这种情况?
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main(int argc,char **argv)
{
int fd[2];
pid_t childpid;
pipe(fd);
childpid=fork();
if (childpid == -1)
{
perror("Error forking...");
exit(1);
}
if (childpid) /*parent proces*/ //grep .c
{
wait(&childpid); //waits till the child send output to pipe
close(fd[1]);
close(0); //stdin closed
dup2(fd[0],0);
execlp(argv[2],argv[2],argv[3],NULL);
}
if (childpid==0) //ls
{
close(fd[0]); /*Closes read side of pipe*/
close(1); //STDOUT closed
dup2(fd[1],1);
execl(argv[1],NULL);
}
return 0;
}
If i give command line argument as "ls grep .c" i should get all the ".c" files displayed.
Pseudocode:-
My child process will run "ls" & parent process will run "grep .c"..
Parent process waits till the child process completes so that child writes to the pipe.
Test run:-
bash-3.1$ ls | grep .c
1.c
hello.c
bash-3.1$ ./a.out ls grep .c
bash-3.1$
Why is that happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一个简单的错误:您的
execl
调用实际上应该是execlp
。此外,您可以摆脱wait
和close
语句。然后你应该检查execlp
的错误代码。A simple mistake: your
execl
call should actually beexeclp
. Besides, you can get rid of thewait
andclose
statements. Then you should check the error code ofexeclp
.另一件事,
close(0)
和close(1)
是不必要的,dup2() 函数会自动为您执行此操作。One more thing, the
close(0)
andclose(1)
are unnecessary, the dup2() function automatically does that for you.实现管道的代码请参考下面问题中的答案。
使用 c 在 Linux 中实现管道
Please refer answer in the question below for the code to implement pipe.
Pipe implementation in Linux using c