我設法使用下面的代碼來建立一個守護進程。我的問題是我想創建一個腳本來啓動這個守護進程並將守護進程PID存儲在/var/run/mydaemon.pid
中。此外,第二個腳本通過訪問存儲的mydaemon.pid
文件來停止守護進程。簡單的腳本來啓動一個守護進程的商店pid
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1
static void daemonize(void)
{
pid_t pid, sid;
/* already a daemon */
if (getppid() == 1) return;
/* Fork off the parent process */
pid = fork();
if (pid < 0) {
exit(EXIT_FAILURE);
}
/* If we got a good PID, then we can exit the parent process. */
if (pid > 0) {
exit(EXIT_SUCCESS);
}
/* At this point we are executing as the child process */
/* Change the file mode mask */
umask(0);
/* Create a new SID for the child process */
sid = setsid();
if (sid < 0) {
exit(EXIT_FAILURE);
}
/* Change the current working directory. This prevents the current
directory from being locked; hence not being able to remove it. */
if ((chdir("/")) < 0) {
exit(EXIT_FAILURE);
}
/* Redirect standard files to /dev/null */
freopen("/dev/null", "r", stdin);
freopen("/dev/null", "w", stdout);
freopen("/dev/null", "w", stderr);
}
int main(int argc, char *argv[]) {
daemonize();
/* Now we are a daemon -- do the work for which we were paid */
return 0;
}
我環顧四周,似乎無法找到示例代碼來幫助我。我得到的最接近的東西是你在下面看到的東西。但它不起作用。
#!/bin/sh
set -e
# Must be a valid filename
NAME=mydaemon
PIDFILE=/var/run/$NAME.pid
DAEMON=/home/me/mydaemon/mydaemon/a.out
export PATH="${PATH:+$PATH:}/usr/sbin:/sbin"
case "$1" in
start)
echo -n "Starting daemon: "$NAME
start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON
echo "."
;;
*)
echo "Usage: "$1" {start}"
exit 1
esac
exit 0
「*它沒有工作。*」是或多或少的價值麻煩報告可以給。 – alk
讓守護進程調用'getpid()',並將結果打印到'/ var/run/mydeamon.pid'? – alk
相關:http://stackoverflow.com/q/3957242/694576 http://stackoverflow.com/q/24662327/694576 – alk