简体   繁体   中英

C how to use exec with linux commands and pipes

I need to execute the following Linux commands : ls -la | sort | wc -l and i have to use exec functions ... Here is my code:

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

Thanks for your time!

Try executing the following args instead:

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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