虽然你应该了解fork()
exec()
wait()
和kill()
,它有时会更方便,只需使用daemon(3)
如果它存在。
注意事项:
- 不在POSIX.1-2001
- 并非存在于所有的BSD的(可能被命名为别的东西,不过)
如果可移植性不是主要问题,这很方便。如果可移植性是是一个主要问题,您可以随时编写自己的实现并使用它。
从手册页:
SYNOPSIS
#include <unistd.h>
int daemon(int nochdir, int noclose);
DESCRIPTION
The daemon() function is for programs wishing to detach themselves from the
controlling terminal and run in the background as system daemons.
If nochdir is zero, daemon() changes the calling process's current working directory
to the root directory ("/"); otherwise, the current working directory is left
unchanged.
If noclose is zero, daemon() redirects standard input, standard output and standard
error to /dev/null; otherwise, no changes are made to these file descriptors.
什么,你的意思是我必须保存在一个文件中的应用程序的PID值,这样,如果我要终止的应用程序,我刚才读的价值和使用在同一代码文件中使用kill shell命令杀死应用程序的值? – domlao 2010-06-04 01:57:44
@sasayins:如果你正在从另一个程序(不是脚本)中杀死进程,应该使用'kill(2)'函数。如果你想杀死父进程的子进程,不需要PID文件,因为fork将PID返回给父进程。 – 2010-06-04 02:07:55