Home > front end >  C Starting daemon as external programm?
C Starting daemon as external programm?

Time:02-26

I have a C Linux programm which uses fork() to run as a daemon and (once daemon runs fine) ends itself.

Now I would like to do the same for an external program.

This should be the workflow:

  1. start launcher program
  2. launch internal daemon
  3. start external program which itself will use fork() and run as daemon
  4. exit launcher program

The internal daemon should be able to monitor the external daemon and check if it is up and running if possible. No direct communication between these two should appear (they will communicate through MQTT).

Parts 1. and 2. are fine so far. Now I read about exec() to start external programs but in this case the caller would never return as is waiting for the called program to exit.

Am I right about the following for 3.? Do exec() and start the program. The program itself will do a fork() and run in background, parent process will exit and thus the launcher program will exit, too. But isn't the exit of the called program treated as an error for exec()?

Thanks a lot!

/KNEBB

CodePudding user response:

I see two possible approaches.

First approach:

1. Start launcher
     |
2. fork() --(child)--> Internal daemon process.
     |(parent)
3. exec()
   External program (replacing launcher)
     |
   fork() --(child)--> External daemon process.
     |(parent)
4. exit()

Second approach:

1. Start launcher
     |
2. fork() --(child)--> Internal daemon process.
     |(parent)
3. fork() ---------->(child)
     |(parent)         |
     |               exec()
     |               External main (background) process
4. exit()

The difference between the approaches is where the second fork occurs. In the first approach, the launcher and the external program both fork child processes and their parents exit. In the second approach, the launcher forks two child processes and the external program does not fork. In both approaches, two child daemon processes are left behind and their parents have exited, so they both get re-parented to the init process (PID 1).

CodePudding user response:

1. Start launcher
     |
2. fork() ------  (child)
     |(launcher)    |
3.  exit()        fork() -->internal daemon
                    |(child) 
4.                exec() ---> external program
                                  |
                               fork() ----------- external daemon 
                                  |
                               exit()

Well, thinking twice about this I think your suggestion is the better one. In both cases the daemon processes get re-parented anyways, right? Any in neither case I can really monitor the other daemon, correct?

Thanks again!

  • Related