将两个命令与管道组合在一起

我试图在一个(不存在的)命令中“合并”两个命令并管道它。我的意思是..假设你有这两个命令: grep text out.txt grep text out.txt ,可以表示这两个命令的(不存在)命令可能类似于(grepwc -l < file.txt) ,然后将行数输出到out.txt中。 基本上这些(grepwc)命令应该与grep text out.txt具有相同的行为 grep text out.txt但更短。

我尝试过这样的事情,但我认为我的方法远远不能实现目标。 我使用名为commlist的结构,其中包含已由cmd,argc和argv解析的命令。 inputfile和outputfile是open()上使用的文件的路径名。

我正在使用的结构。

 typedef struct command { char *cmd; int argc; char *argv[MAXARGS+1]; struct command *next; } COMMAND; 

和代码:

 void execute(COMMAND *commlist) { int fd[2]; pid_t pid; int n_pipes=2; //pipes needed COMMAND *aux = commlist; int i; for(i=0;i<n_pipes; i++){ int oldfd = 0; if(fd[0]!=0){ close(fd[1]); oldfd = fd[0]; } pipe(fd); if((pid=fork())cmd == "grepwc"){ if(i==0){ if(execlp("grep","grep","celio",NULL)<0){ perror("Bad command"); exit(1); } } if(i==1){ if(execlp("wc","wc","-l",NULL) < 0){ perror("Bad command"); exit(1); } } } }//child } } 

完整代码在这里:

http://pastebin.com/tYGWwUjS

http://pastebin.com/sNJhEg2Y

你的方法确实有点过于复杂。 这可以通过一个子进程和一个管道来实现(就像在原始shell命令中一样)。 我们来看看吧:

 grep text < file.txt | wc -l > out.txt 

这个

  • 创建一个管道
  • 分叉两个过程
  • 使grep写入管道
  • 使wc从管道读取

但是只分叉一个进程就足够了,因为我们不需要返回父进程。 这导致以下代码:

 #include  #include  int main (void) { int fd[2]; pipe(fd); if (fork()) { // Child process dup2(fd[0], 0); // wc reads from the pipe close(fd[0]); close(fd[1]); execlp("wc", "wc", "-l", NULL); } else { // Parent process dup2(fd[1], 1); // grep writes to the pipe close(fd[0]); close(fd[1]); execlp("grep", "grep", "celio", NULL); } exit(EXIT_FAILURE); } 

只有当其中一个execlp()失败时才会到达exit()