Abhishek
Abhishek

Reputation:

Can we start a background process using exec() giving & as an argument?

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

Upvotes: 7

Views: 20842

Answers (3)

Kevin Peterson
Kevin Peterson

Reputation: 7297

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

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

Upvotes: 5

R Samuel Klatchko
R Samuel Klatchko

Reputation: 76531

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.

Upvotes: 9

unwind
unwind

Reputation: 399753

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.

Upvotes: 5

Related Questions