int _pidfile_remove(struct pidfh *pfh, int freeit) { int error; error = pidfile_verify(pfh); if (error != 0) { errno = error; return (-1); } if (unlink(pfh->pf_path) == -1) error = errno; if (close(pfh->pf_fd) == -1) { if (error == 0) error = errno; } if (freeit) free(pfh); else pfh->pf_fd = -1; if (error != 0) { errno = error; return (-1); } return (0); }
int pidfile_write(struct pidfh *pfh) { char pidstr[16]; int error, fd; errno = pidfile_verify(pfh); if (errno != 0) { return (-1); } fd = pfh->pf_fd; if (ftruncate(fd, 0) == -1) { error = errno; _pidfile_remove(pfh, 0); errno = error; return (-1); } snprintf(pidstr, sizeof(pidstr), "%u", getpid()); if(pwrite(fd, pidstr, strlen(pidstr), 0) != (size_t)strlen(pidstr)) { error = errno; _pidfile_remove(pfh, 0); errno = error; return (-1); } return (0); }
int core_pidof(lua_State *L) { const char *path = NULL, *key= NULL ; int pid; int top = lua_gettop(L); if (top == 0) { lua_pushnil(L); lua_pushfstring(L, "wrong number of arguments for '%s'", "core_pidof"); return 2; } if (top > 0) path = lua_tostring(L, 1); if (top > 1) key = lua_tostring(L, 2); if (pidfile_exists(path) == UGERR) { lua_pushnil(L); lua_pushfstring(L, "cannot find the pidfile '%s'", path); return 2; } if (pidfile_getpid(path, &pid) == UGERR) { lua_pushnil(L); lua_pushfstring(L, "get pid failed by pidfile '%s'", path); return 2; } if (pidfile_verify(path) == UGOK || (key != NULL && proc_isrunning(pid, key) == UGOK)) { lua_pushinteger(L, pid); return 1; } lua_pushnil(L); return 1; }
static int _pidfile_remove(struct pidfh *pfh, int freeit) { int error; error = pidfile_verify(pfh); if (error != 0) { errno = error; return (-1); } if (funlinkat(pfh->pf_dirfd, pfh->pf_filename, pfh->pf_fd, 0) == -1) { if (errno == EDEADLK) return (-1); error = errno; } if (close(pfh->pf_fd) == -1 && error == 0) error = errno; if (close(pfh->pf_dirfd) == -1 && error == 0) error = errno; if (freeit) free(pfh); else pfh->pf_fd = -1; if (error != 0) { errno = error; return (-1); } return (0); }
int pidfile_close(struct pidfh *pfh) { int error; error = pidfile_verify(pfh); if (error != 0) { errno = error; return (-1); } if (close(pfh->pf_fd) == -1) error = errno; free(pfh); if (error != 0) { errno = error; return (-1); } return (0); }
int pidfile_write(struct pidfh *pfh) { char pidstr[16]; int error, fd; /* * Check remembered descriptor, so we don't overwrite some other * file if pidfile was closed and descriptor reused. */ errno = pidfile_verify(pfh); if (errno != 0) { /* * Don't close descriptor, because we are not sure if it's ours. */ return (-1); } fd = pfh->pf_fd; /* * Truncate PID file, so multiple calls of pidfile_write() are allowed. */ if (ftruncate(fd, 0) == -1) { error = errno; _pidfile_remove(pfh, 0); errno = error; return (-1); } snprintf(pidstr, sizeof(pidstr), "%u", getpid()); if (pwrite(fd, pidstr, strlen(pidstr), 0) != (ssize_t)strlen(pidstr)) { error = errno; _pidfile_remove(pfh, 0); errno = error; return (-1); } return (0); }