我正在尝试学习如何在C中使用pipe()命令,并尝试创建一个测试程序来复制ls的功能. grep“.c”,如果我要将它输入
linux终端.如果我把它输入终端,我只得到test.c.
我的代码如下:
#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"
#include "fcntl.h"
int main(int argc, char** argv)
{
int pipefd[2];
int childpid,childpid2;
char* cmd[3]={"ls",NULL,NULL};
char* cmd2[3]={"grep",".c",NULL};
pipe(pipefd);
if(childpid=fork()){
//parent
}else{
//child
//write
close(pipefd[0]);
dup2(pipefd[1],STDOUT_FILENO);
execvp("ls", cmd);
}
if(childpid2=fork()){
}
else{
close(pipefd[1]);
dup2(pipefd[0],STDIN_FILENO);
execvp("grep",cmd2);
}
close(pipefd[0]);
close(pipefd[1]);
return 0;
}
此代码返回以下结果($是终端提示符):
$a.out
$test.c
(blank line)
该程序没有完成,但挂起,直到我退出它.我有什么问题?我怎么能模仿终端?我是C的新手,并且使用程序的预制模板,如果有明显的错误,请原谅我.