static int _fd_lock_retry(int fd) { int i, rc; for (i = 0; i < 10; i++) { if (i) usleep(1000); /* 1000 usec */ rc = fd_get_write_lock(fd); if (rc == 0) break; if ((errno != EACCES) && (errno != EAGAIN)) break; /* Lock held by other job */ } return rc; }
int create_pidfile(const char *pidfile, uid_t uid) { FILE *fp; int fd = -1; xassert(pidfile != NULL); xassert(pidfile[0] == '/'); if (!(fp = fopen(pidfile, "w"))) { error("Unable to open pidfile `%s': %m", pidfile); return -1; } fd = fileno(fp); if (fd_get_write_lock(fd) < 0) { error ("Unable to lock pidfile `%s': %m", pidfile); fd = -1; goto error; } if (fprintf(fp, "%lu\n", (unsigned long) getpid()) == EOF) { error("Unable to write to pidfile `%s': %m", pidfile); fd = -1; goto error; } fflush(fp); if (uid && (fchown(fd, uid, -1) < 0)) error ("Unable to reset owner of pidfile: %m"); return fd; error: (void)fclose(fp); /* Ignore errors */ if (unlink(pidfile) < 0) error("Unable to remove pidfile `%s': %m", pidfile); return -1; }