C 如何将 exec 与 linux 命令和管道一起使用

C how to use exec with linux commands and pipes

我需要执行以下 Linux 命令:ls -la |排序 | wc -l 并且我必须使用 exec 函数...这是我的代码:

x = fork();

char * args[] = { "ls", "-la" , "|", "sort" , "|" , "wc", "-l" };

if(x == 0){ //Father    
 //Dad validations


}else{      

    execlp(args[0],args[0], args[1],args[2],args[3],args[4],args[5],args[6], NULL);
    perror("Exec error\n");

    exit(1);
 }

这些命令分开工作正常,但是当我将它们放在一起时,我收到此错误消息:

  ls: cannot access |: No such file or directory

  ls: cannot access sort: No such file or directory

我猜错误出在 Linux 管道

感谢您的宝贵时间!

尝试执行以下参数:

char * args[] = { "bash", "-c" , "ls -la | sort | wc -l" };

这是必要的,因为您要使用的管道语法(以及从一个进程到另一个进程的输出管道)实际上是 shell 的一项功能。因此,为了能够 execlp 以这种方式格式化的命令,我们需要执行 shell (在本例中为 bash )并将您的命令作为带有 [= 的字符串提供给它13=]旗帜。