Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the pidfile library correctly?

I already read the man page of the pidfile function family. But I don't really understand it. What is the correct usage? Is there a more elaborate example available? I think I understand pidfile_open. But when should I call pidfile_write and prdfile_close? From which process? Parent or child? What parameters do I have to pass to those functions? I propably lack some *nix fundamentals I guess.

Update:

Below you see the example from man pidfile. Why do they fork twice? Why pidfile_close? When I call pidfile_close I can start another daemon. Isn't that unwanted?

 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);
like image 259
Jan Deinhard Avatar asked Sep 14 '10 07:09

Jan Deinhard


1 Answers

The problem is that you want to give an error message before the daemon is spawned, and that you know the PID file after the daemon is spawned.

So you typically do the pidfile_open before the fork, which gives you a possibility to give an error message. After you forked, you know the pidfile and you can do pidfile_write.

like image 152
Sjoerd Avatar answered Oct 01 '22 18:10

Sjoerd