From e73a8e85878ddd5e60075b8b6daca5d52c6dbd06 Mon Sep 17 00:00:00 2001 From: Shuanglei Tao Date: Sat, 11 May 2019 09:48:16 +0800 Subject: [PATCH] protocol: cleanup process without hanging --- src/protocol.c | 10 +++++----- src/server.c | 10 ++++++++++ src/utils.c | 18 ++++++++++++++++++ src/utils.h | 4 ++++ 4 files changed, 37 insertions(+), 5 deletions(-) diff --git a/src/protocol.c b/src/protocol.c index b3f9a33..dab0d3a 100644 --- a/src/protocol.c +++ b/src/protocol.c @@ -9,7 +9,6 @@ #include #include #include -#include #include #if defined(__OpenBSD__) || defined(__APPLE__) @@ -148,10 +147,11 @@ tty_client_destroy(struct tty_client *client) { if (kill(pid, server->sig_code) != 0) { lwsl_err("kill: %d, errno: %d (%s)\n", pid, errno, strerror(errno)); } - int status; - while (waitpid(client->pid, &status, 0) == -1 && errno == EINTR) - ; - lwsl_notice("process exited with code %d, pid: %d\n", status, client->pid); + pid_t pid_out; + int status = wait_proc(client->pid, &pid_out); + if (pid_out > 0) { + lwsl_notice("process exited with code %d, pid: %d\n", status, pid_out); + } close(client->pty); cleanup: diff --git a/src/server.c b/src/server.c index 413d9b9..73c07ab 100644 --- a/src/server.c +++ b/src/server.c @@ -181,6 +181,15 @@ sig_handler(int sig) { lwsl_notice("send ^C to force exit.\n"); } +void +sigchld_handler() { + pid_t pid; + int status = wait_proc(-1, &pid); + if (pid > 0) { + lwsl_notice("process exited with code %d, pid: %d\n", status, pid); + } +} + int calc_command_start(int argc, char **argv) { // make a copy of argc and argv @@ -456,6 +465,7 @@ main(int argc, char **argv) { signal(SIGINT, sig_handler); // ^C signal(SIGTERM, sig_handler); // kill + signal(SIGCHLD, sigchld_handler); context = lws_create_context(&info); if (context == NULL) { diff --git a/src/utils.c b/src/utils.c index c4330ef..680518c 100644 --- a/src/utils.c +++ b/src/utils.c @@ -4,6 +4,8 @@ #include #include #include +#include +#include #ifdef __linux__ // https://github.com/karelzak/util-linux/blob/master/misc-utils/kill.c @@ -83,6 +85,22 @@ get_sig(const char *sig_name) { return atoi(sig_name); } +int +wait_proc(pid_t in, pid_t *out) { + int stat = 0, pid; + do { + pid = waitpid(in, &stat, WNOHANG); + } while (pid < 0 && errno == EINTR); + if (out != NULL) *out = pid; + int status = -1; + if (WIFEXITED(stat)) { + status = WEXITSTATUS(stat); + } else if (WIFSIGNALED(status)) { + status = WTERMSIG(stat); + } + return status; +} + int open_uri(char *uri) { #ifdef __APPLE__ diff --git a/src/utils.h b/src/utils.h index 1781c6a..72cfce2 100644 --- a/src/utils.h +++ b/src/utils.h @@ -25,6 +25,10 @@ get_sig_name(int sig, char *buf, size_t len); int get_sig(const char *sig_name); +// waitpid with WNOHANG and return the status +int +wait_proc(pid_t in, pid_t *out); + // Open uri with the default application of system int open_uri(char *uri); -- 2.43.4