1

I've done a fork and and then an exec but I don't know how to start it in the background.

Should I use an argument after the exec? If so, which is it?

alk
  • 69,737
  • 10
  • 105
  • 255
Pino
  • 619
  • 1
  • 8
  • 25
  • http://stackoverflow.com/questions/116701/how-can-a-c-c-program-put-itself-into-background – Mr Vinagi Jun 27 '15 at 09:28
  • Which platform are you trying this on, please? – alk Jun 27 '15 at 09:37
  • For at least Linux (or BSD) see: http://man7.org/linux/man-pages/man3/daemon.3.html – alk Jun 27 '15 at 09:40
  • oh sorry, i'm using linux – Pino Jun 27 '15 at 09:40
  • possible duplicate of [running a process in background in c](http://stackoverflow.com/questions/18916656/running-a-process-in-background-in-c) – A B Jun 27 '15 at 09:45
  • duplicate of http://stackoverflow.com/questions/18916656/running-a-process-in-background-in-c – A B Jun 27 '15 at 09:45
  • @AB: I feel in the question you linked the accepted answer is wrong. As the `fork()`ed process is not backgrounded. – alk Jun 27 '15 at 09:58
  • You might also consider changing directory to somewhere on the root filesystem as a daemon so that your long-running background process doesn't prevent filesystems being dismounted. – Mark Setchell Jun 27 '15 at 10:11
  • @AB: Referring my previous commet: "*wrong*" as answer to this question here. So the question you linked is not a duplicate to this one here. – alk Jun 27 '15 at 10:13

1 Answers1

2

If you simply want to background a process use daemon().

If you want to spawn off a process that then backgrounds itself 1st use fork() and inside this 1st child call fork() again letting the 2nd child call exec*() for the process to be backgrounded. Let the initial parent wait() for the 1st child.

As the parent of the second child (the process fork()ed 1st) dies, the exec*()ed process will be reaped by init.


Note: The pattern above is sometimes referred to as "double-forking". See also here: Why fork() twice (and links from there)

Another interesting set of answers on this is here: Linux: Difference between forking twice and daemon(ise)

Community
  • 1
  • 1
alk
  • 69,737
  • 10
  • 105
  • 255
  • @BasileStarynkevitch: Hu Basile, how fast, I was just about to add the links ... :-) Thx! – alk Jun 27 '15 at 09:55