If not, how can we start a background process in C?
Use the fork()
call to create a new process, then exec() to load a program into that process. See the man pages (man 2 fork
, man 2 exec
) for more information, too.
In Unix, exec() is only part of the story.
exec() is used to start a new binary within the current process. That means that the binary that is currently running in the current process will no longer be running.
So, before you call exec(), you want to call fork() to create a new process so your current binary can continue running.
Normally, to have the current binary wait for the new process to exit, you call one of the wait*() family. That function will put the current process to sleep until the process you are waiting is done.
So in order to create a "background" process, your current process should just skip the call to wait.
Fork returns the PID of the child, so the common idiom is:
if(fork() == 0)
// I'm the child
exec(...)