简体   繁体   中英

Emulate shell command line in C

I want to emulate the following shell command line in C, with execl():

find . -type f -ls | cut -d " " -f 3- | sort -n -k 6 >file.txt ; less <file.txt

I wrote each of them as:

execl("/usr/bin/find", "find", ".", "-type", "f", "-ls", (char *)NULL);
execl("/usr/bin/cut", "cut", "-d", "" "", "-f", "3-", (char *)NULL);
execl("/usr/bin/sort", "sort", "-n", "-k", "6", ">file.txt", (char *)NULL);
execl("/usr/bin/less", "less", "<file.txt", (char *)NULL);

I also implemented the pipelines but I am getting an error:

cut: cut: -: Input/Output error -: Input/output error

Any idea what it means? Thanks

All redirections, be them pipes ( | ) or redirection to files ( < , << , > , >> , etc.) are only processed by the shell. When you pass them in an execx call, they are simply passed as an additional argument to the new program.

And anyway, execl replaces the original program by the new one, so anything after execl in never executed unless execl returned an error. The correct way is to setup pipes for the inter process communications, fork to get the number of processes, redirect standard io to the pipes, and only then exec the new programs.

This:

 "" ""

does not create a string holding a double-quoted string. It creates an empty string, by concatenating one empty string (the first "" pair) with another empty string (the second "" pair). Remember that C automatically concatenates adjacent double-quoted string literals ( "foo" "bar" is the same as "foobar" ).

The quotes shouldn't be passed to cut , anyways. You meant:

" "

Update: On the other hand, it's quite possible that you shouldn't be quoting this space after all. The exec() family of functions don't go through a shell by default, and the quoting is for the shell. You really want to pass a space to cut , so you should do so directly with " " .

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