I don't want to use system() in my C program, because system(3) blocks and this is not what I want. What is the optimal way to do it?
5 Answers
I think that a quick and dirty action is to call sytem(command &). the & will spawn the new process.

- 6,608
- 25
- 79
- 153
-
Absolutely +1. `system()` is platform-dependent anyway. Instead of making a mess of your source with `fork()` or stuff like that, use the shell that `system()` gives you access to. – DevSolar Oct 01 '10 at 11:25
-
Use fork()
to create a new process and then use system()
(or any exec
function) in it. The original process will then be able to continue executing.

- 69,862
- 18
- 95
- 117
The answer depends on what your real goal is. You don't say what platform you're on, and I know very little about Windows, so this only covers your options on linux/unix.
You just want to spawn another program, and don't need to interact with it. In this case, call
fork()
, and then in the child process runexecve()
(or related function).You want to interact with another program. In this case, use
popen()
.You want part of your program to run as a subprocess. In this case, use
fork()
, and call whatever functions you need to run in the child.You need to interact with part of your program running as a subprocess. Call
pipe()
so you have a file descriptor to communicate through, then callfork()
and use the file descriptor pair to communicate. Alternatively, you could communicate through a socket, message queue, shared memory, etc.

- 30,042
- 15
- 70
- 103
-
Nice rundown of the options at hand, and how to choose between them. – Matt Joiner Oct 01 '10 at 16:01
-
`fork()` then `system()` will leave a useless process hanging around for the shell to finish. It is better to call `execve()` or similar in the child process instead of `system()`. If you want to use the shell's features, then exec `/bin/sh`. – jilles Oct 02 '10 at 13:39
You might want to use popen
. It creates new processes and allows you to redirect the process output to your own process.

- 36,376
- 13
- 83
- 122
If in windows, use the ShellExecute()
function from the Windows API.
If in Unix, go for fork()
then system()
as mentioned.

- 15,438
- 7
- 38
- 49