C 作为外部程序启动守护进程?
我有一个 C Linux 程序,它使用 fork() 作为守护进程运行,并且(一旦守护进程运行正常)自行结束。
现在我想对外部程序做同样的事情。
这应该是工作流程:
- 启动启动程序
- 启动内部守护程序
- 启动外部程序,该程序本身将使用 fork() 并作为守护程序运行
- 退出启动程序
内部守护程序应该能够监视外部守护程序并检查是否如果可能的话,它已经启动并运行。这两者之间不应出现直接通信(它们将通过 MQTT 进行通信)。
到目前为止,第 1 部分和第 2 部分都很好。现在我读到有关 exec()
来启动外部程序,但在这种情况下,调用者永远不会返回,因为正在等待被调用的程序退出。
我对以下 3 的看法正确吗? 执行 exec() 并启动程序。程序本身将执行fork()
并在后台运行,父进程将退出,因此启动程序也将退出。但是对于exec()
来说,被调用程序的退出不是被视为错误吗?
多谢!
/克内布
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:
- start launcher program
- launch internal daemon
- start external program which itself will use
fork()
and run as daemon - 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我看到两种可能的方法。
第一种方法:
第二种方法:
两种方法之间的区别在于第二个分叉发生的位置。在第一种方法中,启动器和外部程序都分叉子进程并且它们的父进程退出。在第二种方法中,启动器分叉两个子进程,并且外部程序不分叉。在这两种方法中,都会留下两个子守护进程,并且它们的父进程已退出,因此它们都将重新设置为
init
进程 (PID 1) 的父进程。I see two possible approaches.
First approach:
Second approach:
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).好吧,再三考虑,我认为你的建议是更好的。在这两种情况下,守护进程都会重新设置父级,对吧?
在这两种情况下我都不能真正监视另一个守护进程,对吗?
再次感谢!
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!