system() vs fork()/exec() (was Re: mv'ing files from a C program)
Barry Margolin
barmar at think.com
Fri Nov 16 10:23:52 AEST 1990
In article <1990Nov15.183359.963 at ssd.kodak.com> weimer at ssd.kodak.com (Gary Weimer) writes:
>In article <1990Nov15.132952.11932 at virtech.uucp> cpcahil at virtech.UUCP (Conor P. Cahill) writes:
>>You don't have to use system(3), you can use fork/execl(2) (or one of it's
>>family of functions) as follows:
>That's just about exactly what system(3) does. (i.e. you gain nothing for
>all the added code)
There are some performance and behavioral differences. First of all,
system() has to first exec /bin/sh after forking. Second, the shell has to
parse the command line back into individual arguments. Why exec() two
programs when you can exec() one, and parsing arguments that were
originally separate variables is also wasteful. System() is best used when
you are taking the command line from the user.
There are also behavioral differences, and some caveats apply when using
system(). System() does globbing, variable expansion, etc., while these
aren't done by exec(). Whitespace and other special characters can affect
the shell's parse of the command line, so you have to be careful about
quoting when you build the command line for system(), e.g.
char file1[] = "foo bar"
char file2[] = "baz"
char command[COMMAND_LEN];
sprintf(command, "mv %s %s", file1, file2);
system(command);
is not equivalent to a fork followed by
execlp("mv", "mv", file1, file2, (char*)0);
because the first will pass three filename arguments to mv, while the
second will pass only two. You can get around this by putting quotes into
the sprintf() format string, but you'll still have problems if a filename
contains quotes.
--
Barry Margolin, Thinking Machines Corp.
barmar at think.com
{uunet,harvard}!think!barmar
More information about the Comp.unix.questions
mailing list