0

I am looking for C code to use on a Linux based system to start another process asynchronously. The second process should continue, even if the first ends. I've looked through the "fork" and "system" and "exec" options, but don't see anything that will spawn a peer process that's not communicating with or a child of the original process.

Can this be done?

Gatnus
  • 13
  • 1
  • 4
  • 2
    When a parent process dies, its child processes don't die. The child processes get a new parent - `init` process. – Arjun Sreedharan Mar 20 '14 at 18:45
  • 1
    What Arjun said + the process can also orphan itself at will. This is called [`daemonizing`](http://stackoverflow.com/questions/3095566/linux-daemonize) – salezica Mar 20 '14 at 18:46
  • See http://stackoverflow.com/questions/17954432/creating-a-daemon-in-linux for a description on creating a daemon process under Linux. – esorton Mar 20 '14 at 18:49

3 Answers3

2

Certainly you can. In the parent fork() a child, and in that child first call daemon() (which is an easy way to avoid setsid etc.), then call something from the exec family.

abligh
  • 24,573
  • 4
  • 47
  • 84
0

In Linux (and Unix), every process is created by an existing process. You may be able to create a process using fork and then, kill the parent process. This way, the child will be an orphan but still, it gets adopted by init. If you want to create a process that is not inherited by another, I am afraid that may not be possible.

unxnut
  • 8,509
  • 3
  • 27
  • 41
  • In the spirit of keeping with the lingo, the desire to keep the original parent *and* the child, while having the child embrace his new foster parent `init` is done with a *double-fork-exec* model. – WhozCraig Mar 20 '14 at 18:50
0

You do a fork (man 2 fork) followed by an execl (man 2 execl)

For creates a new process of the same image as the calling process (so a perfect twin), where execl replaces one of the twins with a new image.

If you search google for "fork execl" you will find many text book examples -- including how to use correctly fork() and exec()

The most common fork-execl you will still have the new process associated to the terminal -- to create a perfect background process you need to create what is called a daemon process -- the template for that can be fornd in this answer here Creating a daemon in Linux

Community
  • 1
  • 1
Soren
  • 14,402
  • 4
  • 41
  • 67
  • Thanks for the solution. I was thinking that fork execl would create a child process that dies when the parent dies, but now realize it becomes an orphan and keeps on rolling. I actually want the process to continue connected to the console and not as a daemon. Works great! – Gatnus Mar 21 '14 at 12:39
  • @Gatnus best way of tanking for the solution is to up-vote and "accept" the answer you find best describes the solution to your problem :-) – Soren Mar 21 '14 at 22:41