作者:婧氏橙奂 | 来源:互联网 | 2023-08-05 21:05
Iamtryingtolearnhowtousethepipe()commandinC,andtryingtocreateatestprogramtodupl
I am trying to learn how to use the pipe() command in C, and trying to create a test program to duplicate the functionality of ls | grep ".c"
, if I were to enter this into a linux terminal. If I enter this into the terminal, I only get test.c
as a result.
我试图学习如何在C中使用pipe()命令,并尝试创建一个测试程序来复制ls的功能。 grep“.c”,如果我要将它输入linux终端。如果我将它输入终端,我只得到test.c。
My code is as follows:
我的代码如下:
#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;
}
This code returns me the following results ($ is the terminal prompt):
此代码返回以下结果($是终端提示符):
$a.out
$test.c
(blank line)
The program doesn't complete, but hangs until I quit it. What problems do I have? How can I mimic the terminal? I'm new to C, and using a premade template of a program, so forgive me if there are glaring mistakes.
该程序没有完成,但挂起,直到我退出它。我有什么问题?我怎么能模仿终端?我是C的新手,并使用程序的预制模板,如果有明显的错误,请原谅我。
3 个解决方案