~ 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. */
| 644 | * daemons on the same database at once, but lets nosy sysadmins see what pid |
| 645 | * the currently-running daemon is supposed to be. */ |
| 646 | static void pidfile_create(const struct lightningd *ld) |
| 647 | { |
| 648 | int pid_fd; |
| 649 | char *pid; |
| 650 | |
| 651 | /* Create PID file: relative to .config dir. */ |
| 652 | pid_fd = open(ld->pidfile, O_WRONLY|O_CREAT, 0640); |
| 653 | if (pid_fd < 0) |
| 654 | err(1, "Failed to open PID file"); |
| 655 | |
| 656 | /* Lock PID file, so future lockf will fail. */ |
| 657 | if (lockf(pid_fd, F_TLOCK, 0) < 0) |
| 658 | /* Problem locking file */ |
| 659 | err(EXITCODE_PIDFILE_LOCK, "lightningd already running? Error locking PID file"); |
| 660 | |
| 661 | /*~ As closing the file will remove the lock, we need to keep it open; |
| 662 | * the OS will close it implicitly when we exit for any reason. */ |
| 663 | |
| 664 | /*~ Note that tal_fmt() is what asprintf() dreams of being. */ |
| 665 | pid = tal_fmt(tmpctx, "%d\n", getpid()); |
| 666 | /*~ CCAN's write_all writes to a file descriptor, looping if necessary |
| 667 | * (which, on a file unlike a socket, is never, for historical UNIX |
| 668 | * reasons). It also isn't declared with GCC's warn_unused_result |
| 669 | * which write() is when FORTIFY_SOURCE is defined, so we're allowed |
| 670 | * to ignore the result without jumping through hoops. */ |
| 671 | write_all(pid_fd, pid, strlen(pid)); |
| 672 | } |
| 673 | |
| 674 | /*~ ccan/io allows overriding the poll() function that is the very core |
| 675 | * of the event loop it runs for us. We override it so that we can do |