【发布时间】:2011-04-12 00:58:03
【问题描述】:
我已经阅读了 pidfile 函数系列的手册页。但我真的不明白。正确的用法是什么?是否有更详细的示例可用?我想我理解pidfile_open。但是我什么时候应该打电话给pidfile_write 和prdfile_close?来自哪个过程?父母还是孩子?我必须将哪些参数传递给这些函数?我猜我可能缺乏一些 *nix 基础知识。
更新:
下面是 man pidfile 中的示例。为什么他们分叉两次?为什么要使用 pidfile_close?当我调用 pidfile_close 时,我可以启动另一个守护进程。这不是不需要的吗?
struct pidfh *pfh;
pid_t otherpid, childpid;
pfh = pidfile_open("/var/run/daemon.pid", 0600, &otherpid);
if (pfh == NULL) {
if (errno == EEXIST) {
errx(EXIT_FAILURE, "Daemon already running, pid: %jd.",
(intmax_t)otherpid);
}
/* If we cannot create pidfile from other reasons, only warn. */
warn("Cannot open or create pidfile");
}
if (daemon(0, 0) == -1) {
warn("Cannot daemonize");
pidfile_remove(pfh);
exit(EXIT_FAILURE);
}
pidfile_write(pfh);
for (;;) {
/* Do work. */
childpid = fork();
switch (childpid) {
case -1:
syslog(LOG_ERR, "Cannot fork(): %s.", strerror(errno));
break;
case 0:
pidfile_close(pfh);
/* Do child work. */
break;
default:
syslog(LOG_INFO, "Child %jd started.", (intmax_t)childpid);
break;
}
}
pidfile_remove(pfh);
exit(EXIT_SUCCESS);
【问题讨论】:
-
您看到的手册页是否有“示例”部分? BSD 可以,这很好地说明了常见用途。请参阅fuse4bsd.creo.hu/localcgi/man-cgi.cgi?pidfile+3,查看“示例”部分。
-
@Tim,手册页包含一个示例,但我无法将其应用于我的守护程序代码。我的守护进程结构不同。例如我不使用函数 daemon(3)。