~ It's pretty standard behaviour (especially for daemons) to create and * file-lock a pidfile. This not only prevents accidentally running multiple * daemons on the same database at once, but lets nosy sysadmins see what pid * the currently-running daemon is supposed to be. */
| 716 | * daemons on the same database at once, but lets nosy sysadmins see what pid |
| 717 | * the currently-running daemon is supposed to be. */ |
| 718 | static void pidfile_create(const struct lightningd *ld) |
| 719 | { |
| 720 | int pid_fd; |
| 721 | char *pid; |
| 722 | |
| 723 | /* Create PID file: relative to .config dir. */ |
| 724 | pid_fd = open(ld->pidfile, O_WRONLY|O_CREAT, 0640); |
| 725 | if (pid_fd < 0) |
| 726 | err(1, "Failed to open PID file"); |
| 727 | |
| 728 | /* Lock PID file, so future lockf will fail. */ |
| 729 | if (lockf(pid_fd, F_TLOCK, 0) < 0) |
| 730 | /* Problem locking file */ |
| 731 | err(EXITCODE_PIDFILE_LOCK, "lightningd already running? Error locking PID file"); |
| 732 | |
| 733 | /*~ As closing the file will remove the lock, we need to keep it open; |
| 734 | * the OS will close it implicitly when we exit for any reason. */ |
| 735 | |
| 736 | /*~ Note that tal_fmt() is what asprintf() dreams of being. */ |
| 737 | pid = tal_fmt(tmpctx, "%d\n", getpid()); |
| 738 | /*~ CCAN's write_all writes to a file descriptor, looping if necessary |
| 739 | * (which, on a file unlike a socket, is never, for historical UNIX |
| 740 | * reasons). It also isn't declared with GCC's warn_unused_result |
| 741 | * which write() is when FORTIFY_SOURCE is defined, so we're allowed |
| 742 | * to ignore the result without jumping through hoops. */ |
| 743 | write_all(pid_fd, pid, strlen(pid)); |
| 744 | } |
| 745 | |
| 746 | /*~ ccan/io allows overriding the poll() function that is the very core |
| 747 | * of the event loop it runs for us. We override it so that we can do |