如何在c中创建一个linux管道示例

ngw*_*ams 6 c linux pipe

我正在尝试学习如何在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;
}
Run Code Online (Sandbox Code Playgroud)

此代码返回以下结果($是终端提示符):

$a.out
$test.c
(blank line)
Run Code Online (Sandbox Code Playgroud)

该程序没有完成,但挂起,直到我退出它.我有什么问题?我怎么能模仿终端?我是C的新手,并且使用程序的预制模板,如果有明显的错误,请原谅我.

Lee*_*hem 5

尝试这个:

#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
   close(pipefd[1]);
   dup2(pipefd[0],STDIN_FILENO);
   execvp("grep",cmd2);
 }else{  
   //child
   //write
   close(pipefd[0]);
   dup2(pipefd[1],STDOUT_FILENO);
   execvp("ls", cmd);
 }
 return 0;
}
Run Code Online (Sandbox Code Playgroud)