代码之家  ›  专栏  ›  技术社区  ›  Jan Deinhard

如何正确使用pidfile库?

  •  8
  • Jan Deinhard  · 技术社区  · 16 年前

    我已经阅读了pidfile函数家族的手册页。但我不太明白。正确的用法是什么?有更详细的例子吗?我想我明白了 pidfile_open . 但是我应该什么时候打电话 pidfile_write 和 prdfile_close ?从哪个过程?父母还是孩子?我必须将哪些参数传递给这些函数?我想我可能缺乏一些基本的知识。

    更新:

    下面是man pidfile中的示例。他们为什么要分两次叉子?为什么要关闭pidfile?当我调用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);
    
    2 回复  |  直到 12 年前
        1
  •  5
  •   Sjoerd    16 年前

    问题是,您希望在生成守护程序之前给出错误消息,并且在生成守护程序之后知道PID文件。

    因此,您通常在fork之前打开pidfile,这使您有可能给出错误消息。分叉后,您知道pidfile,可以进行pidfile_写入。

        2
  •  1
  •   Pawel Jakub Dawidek    12 年前

    在进入后台之前打开pidfile_(3),这样就可以立即报告任何问题。你还没有写pid,因为你的pid会在守护进程(3)之后改变。pidfile_open(3)仅锁定pidfile。在守护进程(3)之后,您可以调用pidfile_write(3),因为您现在有了最终的pid(守护进程(3)在内部分叉)。在主进程中,您不能调用pidfile_close(3),因为这是整个想法——通过保持pidfile打开并锁定,您可以让其他人知道您仍然活着。第二个叉子是完全可选的。它说明守护进程产生子进程/工作进程的常见行为。如果你不使用它们,你就不需要这个叉子()。这个fork()只显示在这样的工作进程中,您应该关闭pidfile,所以它只由主进程而不是子进程保持打开和锁定。