Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

There appear to be two common ways of running an external executable from C in unix, the

system()

call and

pid = fork()
switch(pid)
//switch statement based on return value of pid, 
//one branch of which will include and exec() command

Is there any reason to prefer a fork/exec over system in the case where they are functionally equivalent (parent process waits for child to finish, no complex information is returned from child)?.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
332 views
Welcome To Ask or Share your Answers For Others

1 Answer

system executes a command-interpreter, i.e. a shell, which (a) is slower than a direct fork/exec, (b) may behave differently on different systems and (c) is a potential security hazard if you pass it a string from an untrusted source. Also, system waits for the child process to exit, while you might want it to run concurrently with the parent process.

More in general, the low-level fork/exec gives you additional control: before or in between the two operations, you might want to chdir, open pipes, close file descriptors, set up shared memory, etc.

(By different systems, I don't mean Windows vs. Unix (as Windows doesn't even have fork): I'm talking Red Hat Linux vs. Ubuntu. The former uses Bash to execute what is passed to system, the latter a lightweight POSIX-compatible shell.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...