What's the difference between calling daemon() and calling fork(), setsid(), fork(), etc.?

百般思念 提交于 2019-12-30 00:36:13

问题


I've been looking at creating Unix dæmons, and there seem to be two methods. The long-winded one, which seems to come up when searching is to call fork(), setsid(), fork() again, chdir() to somewhere safe, set umask() and, finally, close() stdin, stdout and stderr.

Running man daemon, however, brings up information on a daemon() function, which seems to do all the same stuff as above. Are there any differences between the two approaches or is daemon() just a convenience function that does the same thing as the long-winded method? Is either one better, especially for a novice C programmer?


回答1:


The daemon function is not defined in POSIX, so its implementation (if any) could behave differently on different platforms.

On Linux with glibc, daemon only does one fork, optionally chdirs (but only to /, you can't specify a path), does not touch umask, and does not close the std* descriptors (it optionally reopens them to /dev/null though). (source)

So it depends on the platform, and at least one implementation does less than what you do. If you need all of what you're doing, stick with that (or stick to a platform where the daemon function does exactly that).




回答2:


Note that daemon is not conforming to any standard. Better use standard conforming functions (like POSIX-defined fork and setsid).




回答3:


The daemon call summarizes the long-winded fork procedure, and I don't recall any implementation that does anything more.

Since daemon() is a high-level concept, it's definitely to be preferred for novice and experienced programmers.



来源:https://stackoverflow.com/questions/7645378/whats-the-difference-between-calling-daemon-and-calling-fork-setsid-for

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!