1144 Chapter 55
int
createPidFile(const char *progName, const char *pidFile, int flags)
{
int fd;
char buf[BUF_SIZE];
fd = open(pidFile, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
if (fd == -1)
errExit("Could not open PID file %s", pidFile);
if (flags & CPF_CLOEXEC) {
/* Set the close-on-exec file descriptor flag */
flags = fcntl(fd, F_GETFD); /* Fetch flags */
if (flags == -1)
errExit("Could not get flags for PID file %s", pidFile);
flags |= FD_CLOEXEC; /* Turn on FD_CLOEXEC */
if (fcntl(fd, F_SETFD, flags) == -1) /* Update flags */
errExit("Could not set flags for PID file %s", pidFile);
}
if (lockRegion(fd, F_WRLCK, SEEK_SET, 0, 0) == -1) {
if (errno == EAGAIN || errno == EACCES)
fatal("PID file '%s' is locked; probably "
"'%s' is already running", pidFile, progName);
else
errExit("Unable to lock PID file '%s'", pidFile);
}
if (ftruncate(fd, 0) == -1)
errExit("Could not truncate PID file '%s'", pidFile);
snprintf(buf, BUF_SIZE, "%ld\n", (long) getpid());
if (write(fd, buf, strlen(buf)) != strlen(buf))
fatal("Writing to PID file '%s'", pidFile);
return fd;
}
–––––––––––––––––––––––––––––––––––––––––––– filelock/create_pid_file.c
55.7 Older Locking Techniques
In older UNIX implementations that lacked file locking, a number of ad hoc locking
techniques were employed. Although all of these have been superseded by fcntl()
record locking, we describe them here since they still appear in some older pro-
grams. All of these techniques are advisory in nature.