views:

463

answers:

3

If not, how can we start a background process in C?

+3  A: 

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.

unwind
fork and exec has nothing to do with background process
avd
@aditya: Would you care to expand on that? fork() is how to create a new process, which is what you need to do if you want to run something in the background from a C program ...
unwind
@aditya fork has exactly 100% to do with creating a background process. What are you talking about?
Carl Norum
+2  A: 

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.

R Samuel Klatchko
A: 

Fork returns the PID of the child, so the common idiom is:

if(fork() == 0)
    // I'm the child
    exec(...)
Kevin Peterson