Separate process wait and close

On Linux, waitpid() both waits for the process to terminate and reaps it
(closes its handle). On Windows, these actions are separated into
WaitForSingleObject() and CloseHandle().

Expose these actions separately, so that it is possible to send a signal
to a process while waiting for its termination without race condition.

This allows to wait for server termination normally, but kill the
process without race condition if it is not terminated after some delay.
This commit is contained in:
Romain Vimont
2021-01-03 17:06:08 +01:00
parent 821c175730
commit d580ee30f1
4 changed files with 64 additions and 13 deletions

View File

@@ -134,15 +134,21 @@ process_terminate(pid_t pid) {
return kill(pid, SIGTERM) != -1;
}
bool
process_wait(pid_t pid, int *exit_code) {
int status;
static bool
process_wait_internal(pid_t pid, int *exit_code, bool close) {
int code;
if (waitpid(pid, &status, 0) == -1 || !WIFEXITED(status)) {
int options = WEXITED;
if (!close) {
options |= WNOWAIT;
}
siginfo_t info;
int r = waitid(P_PID, pid, &info, options);
if (r == -1 || info.si_code != CLD_EXITED) {
// could not wait, or exited unexpectedly, probably by a signal
code = -1;
} else {
code = WEXITSTATUS(status);
code = info.si_status;
}
if (exit_code) {
*exit_code = code;
@@ -150,6 +156,21 @@ process_wait(pid_t pid, int *exit_code) {
return !code;
}
bool
process_wait(pid_t pid, int *exit_code) {
return process_wait_internal(pid, exit_code, true);
}
bool
process_wait_noclose(pid_t pid, int *exit_code) {
return process_wait_internal(pid, exit_code, false);
}
void
process_close(pid_t pid) {
process_wait_internal(pid, NULL, true);
}
char *
get_executable_path(void) {
// <https://stackoverflow.com/a/1024937/1987178>