雖然你應該瞭解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