6

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

unwind
  • 391,730
  • 64
  • 469
  • 606

3 Answers3

9

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
  • 74,869
  • 16
  • 134
  • 187
  • 2
    Be careful, this creates a zombie process. – Sw0ut Aug 27 '18 at 13:55
  • I suggest to create a thread, then in the thread you can fork and wait for the child. – Sw0ut Aug 27 '18 at 15:47
  • 1
    @Sw0ut - a thread is a very expensive way to prevent a zombie. The standard recommendation is to catch SIGCHLD and then call wait in your signal handler. – R Samuel Klatchko Aug 28 '18 at 17:45
  • @Samuel Klatchko I absolutely needed a thread in my program because 1. It must be async (i just want to run the program in background) 2. I run a large amount of times that child program, which leads to a large amount of zombies (about 6000 in 1 hour if unstopped). With the SIGCHLD it didn't work like expected, it seemed to wait for the end of the child program, maybe bause it was run on the main thread. – Sw0ut Aug 28 '18 at 19:20
4

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
  • 391,730
  • 64
  • 469
  • 606
  • fork and exec has nothing to do with background process – avd Oct 02 '09 at 18:01
  • @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 Oct 02 '09 at 18:05
  • @aditya fork has exactly 100% to do with creating a background process. What are you talking about? – Carl Norum Oct 02 '09 at 22:23
4

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

if(fork() == 0)
    // I'm the child
    exec(...)
Kevin Peterson
  • 7,189
  • 5
  • 36
  • 43