如何正确使用pidfile库?

Jan*_*ard 8 c unix linux daemon pid

我已经阅读了pidfile函数系列的手册页.但我真的不明白.什么是正确的用法?有没有更精细的例子?我想我明白了pidfile_open.但是,当我打电话要pidfile_writeprdfile_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);
Run Code Online (Sandbox Code Playgroud)

Sjo*_*erd 5

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

因此,您通常在fork之前执行pidfile_open,这样您就可以给出错误消息.分叉后,你知道pidfile,你可以做pidfile_write.