c - 如何正确使用pidfile库?

标签 c linux unix daemon pid

我已经阅读了 pidfile 函数系列的手册页。但我真的不明白。正确的用法是什么?有更详细的例子吗?我想我理解 pidfile_open。但是我应该什么时候调用pidfile_writeprdfile_close?来自哪个过程? parent 还是 child ?我必须将哪些参数传递给这些函数?我想我可能缺乏一些 *nix 基础知识。

更新:

下面是来自 man pidfile 的示例。他们为什么 fork 两次?为什么是 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);

最佳答案

问题是你想在生成守护进程之前给出错误消息,而在生成守护进程之后你知道 PID 文件。

所以您通常在 fork 之前执行 pidfile_open,这使您有可能给出错误消息。 fork 后,您知道 pidfile 并且可以执行 pidfile_write。

关于c - 如何正确使用pidfile库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3706956/

相关文章:

unix - 线程安全和异步信号安全的区别

linux - 如何在bash中复制字符串直到另一个字符串

继续迭代/重复 while 循环,直到按下 enter(或任意键)

c - 带有 SEEK_END 和正偏移量的 fseek 的行为?

c++ - 如何检查 C/C++ 中是否存在函数?

linux - 如何防止重复输入创建 cron 作业?

c - 如何终止套接字接受阻塞

c - C 中静态变量的问题

linux - 使用 shell 计算学生的平均分

bash - 带有/空格+ ssh的变量