Why same works for windows and doesn't work for unix?
In windows API to create process we have CreateProcess
function.
Now let's consider we want to create process and run DIR /X
command. Of course in windows there is not executable DIR.exe
and we can't just pass it to CreateProcess
. So what to do?
Solution of this problem is quite simple. We just should pass cmd /C "DIR /X"
(as second argument) to CreateProcess
.
Now lets try to do the same (not with DIR /X
, but with ls |开发者_如何学编程 wc
) in unix.
In unix I'm going to use fork + execvp
to create new process and execute the command. Why I want my command to be ls | wc
, because in unix single commands like ls
, grep
, ps
are executables and can be passed to exec alone (i.e. not as argument of sh
, bash
, ...).
So here again it seems that we can pass "ls | wc"
as argument of sh
. (i.e. we can tokenize sh -c "ls | wc"
and pass them to execvp
). But Oooops, this doesn't work!
char *arg[] = {"sh", "-c", "\"ls | wc\"", NULL};
execvp(arg[0], arg);
So question. How can I resolve this problem?
P.S.
In windows if cygwin is installed cmd /C "ls | wc"
works.
Your list of arguments must be terminated by a NULL pointer.
char *arg[] = {"sh", "-c", "ls | wc", NULL};
You don't need the escaped \"
, this should work just fine:
char *arg[] = {"sh", "-c", "ls | wc", NULL};
The "
are merely for the shell to distinguish which part of the input to "group" into an argument, but you don't need them when making your execvp
call. The effect of your could would be as if you entered "ls | wc"
in your shell, including the double quotes (try it, you'll get ls | wc: command not found
).
It probably would be easier to use system() in your example.
Get rid of the quotes on the argument to sh:
char *arg[] = {"sh", "-c", "ls | wc", NULL};
execvp(arg[0], arg);
精彩评论