简体   繁体   English

C如何在Linux命令和管道中使用exec

[英]C how to use exec with linux commands and pipes

I need to execute the following Linux commands : ls -la | 我需要执行以下Linux命令:ls -la | sort | 排序 wc -l and i have to use exec functions ... Here is my code: 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);
 }

The commands work properly separated, but when i put them together i get this error message: 这些命令可以正确分开工作,但是当我将它们放在一起时,会收到以下错误消息:

  ls: cannot access |: No such file or directory

  ls: cannot access sort: No such file or directory

i guess the error is in the Linux pipe 我猜错误是在Linux管道中

Thanks for your time! 谢谢你的时间!

Try executing the following args instead: 尝试改为执行以下args:

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

This is necessary because the pipe syntax you want to use (and the resulting piping of output from one process to another) is actually a feature of the shell. 这是必需的,因为要使用的管道语法(以及从一个过程到另一个过程的输出结果管道)实际上是Shell的功能。 Thus to be able to execlp a command formatted in that way, we need to execute a shell ( bash in this case) and provide your command to it as a string with the -c flag. 因此,为了能够execlp以这种方式格式化的命令,我们需要执行(壳bash在这种情况下),并把它提供你的命令与字符串-c标志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM