2014-09-27 72 views
0

我是新来的操作系统,我想执行下面提到的下面的命令,但我无法解决它为什么不起作用。执行ls -l | grep D |时出错grep De

我想执行的命令

ls -l | grep D|grep De 

这是我的代码 -

#include<stdio.h> 
#include<stdlib.h> 
#include<unistd.h> 

int main() 
{ 
    int fd[2]; 
    int fd2[2]; 
    pipe(fd); 
    if(!fork()) 
    { 
     pipe(fd2); 
     if(!fork()) 
     { 
      close(0); 
      dup(fd[0]); 
      close(1); 
      close(fd[1]); 
      dup2(fd2[1],fd[0]); 
      close(fd[0]); 
      execlp("grep","grep","D",NULL); 
     } 
     else 
     { 
      close(fd[0]); 
      dup(fd2[0]); 
      close(fd[1]); 
      execlp("grep","grep","De",NULL); 
     } 
    } 

    else 
    { 
     close(1); 
     dup(fd[1]); 
     close(0); 
     execlp("ls","ls","-l",NULL); 
    } 
    return 0; 
} 

请帮我执行此命令。 感谢ü提前

回答

0

下面是从你的C代码执行这些命令的一个更简单的方法:要执行

#include <stdio.h> 
#include <string.h> 

int main() 
{ 
    char command[50]; 

    strcpy(command, "ls -l | grep D|grep De"); 
    system(command); 

    return(0); 
} 

system命令经过命令指定的主机环境的命令名或程序名由命令处理器执行并在命令完成后返回。

这里是执行shell脚本的另一种方式,如果你的命令让你在未来过于复杂:

#include <stdio.h> 
#include <stdlib.h> 

#define SHELLSCRIPT "\ 
ls -l | grep D|grep De" 

int main() 
{ 
puts("Will execute sh with the following script :"); 
puts(SHELLSCRIPT); 
puts("Starting now:"); 
system(SHELLSCRIPT); 
return 0; 
} 

#define SHELLSCRIPT指令在C中定义一个名为常量:SHELLSCRIPT其中包含shell脚本。

每行末尾的反斜杠\用于输入下一行的代码以提高可读性。

如果您有任何问题,请让我知道!