Skip to content

Commit

Permalink
pid_lock: Various tweaks
Browse files Browse the repository at this point in the history
* Support `--pid-file none` to disable multiple
  process checking.
* Save PID after daemonizing (otherwise SIGTERM would
  be sent to non-existent PID if daemonizing is enabled)
  • Loading branch information
updateing committed Mar 7, 2017
1 parent d7a11b1 commit f63c431
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 6 deletions.
1 change: 1 addition & 0 deletions include/pid_lock.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

RESULT pid_lock_init(const char* pidfile);
RESULT pid_lock_lock();
RESULT pid_lock_save_pid();
RESULT pid_lock_destroy();

#endif
6 changes: 5 additions & 1 deletion minieap.c
Original file line number Diff line number Diff line change
Expand Up @@ -205,9 +205,13 @@ int main(int argc, char* argv[]) {
return FAILURE;
}

if (IS_FAIL(pid_lock_lock())) {
return FAILURE;
}

apply_log_daemon_params();

pid_lock_lock();
pid_lock_save_pid();

switch_to_state(EAP_STATE_PREPARING, NULL);

Expand Down
30 changes: 25 additions & 5 deletions util/pid_lock.c
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,21 @@
#include "misc.h"

#define PID_STRING_BUFFER_SIZE 12
#define PID_FILE_NONE "none"

static int pid_lock_fd = 0;
static int pid_lock_fd = 0; // 0 = uninitialized, -1 = disabled

RESULT pid_lock_init(const char* pidfile) {
if (pidfile == NULL) {
return FAILURE;
}

if (strcmp(pidfile, PID_FILE_NONE) == 0) {
PR_WARN("PID 检查已禁用,请确保一个接口上只有一个认证进程")
pid_lock_fd = -1;
return SUCCESS;
}

pid_lock_fd = open(pidfile, O_RDWR | O_CREAT);
if (pid_lock_fd < 0) {
PR_ERRNO("无法打开 PID 文件");
Expand Down Expand Up @@ -52,7 +59,15 @@ static RESULT pid_lock_handle_multiple_instance() {
}
}

static RESULT pid_lock_save_pid() {
RESULT pid_lock_save_pid() {
if (pid_lock_fd == 0) {
PR_WARN("PID 文件尚未初始化");
return FAILURE;
} else if (pid_lock_fd < 0) {
// User disabled pid lock
return SUCCESS;
}

char writebuf[PID_STRING_BUFFER_SIZE];

my_itoa(getpid(), writebuf, 10);
Expand All @@ -66,15 +81,20 @@ static RESULT pid_lock_save_pid() {
}

RESULT pid_lock_lock() {
if (pid_lock_fd <= 0) {
PR_ERR("PID 文件尚未打开");
if (pid_lock_fd == 0) {
PR_WARN("PID 文件尚未初始化");
return FAILURE;
} else if (pid_lock_fd < 0) {
// User disabled pid lock
return SUCCESS;
}

int lock_result = flock(pid_lock_fd, LOCK_EX | LOCK_NB);
if (lock_result < 0) {
if (errno == EWOULDBLOCK) {
if (IS_FAIL(pid_lock_handle_multiple_instance())) {
close(pid_lock_fd);
pid_lock_fd = 0;
return FAILURE;
} // Continue if handled
} else {
Expand All @@ -83,7 +103,7 @@ RESULT pid_lock_lock() {
}
}

return pid_lock_save_pid(); // I don't quite prefer this kind of code...
return SUCCESS;
}

RESULT pid_lock_destroy() {
Expand Down

0 comments on commit f63c431

Please sign in to comment.