我设法使用下面的代码来建立一个守护进程。我的问题是我想创建一个脚本来启动这个守护进程并将守护进程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