Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 60 additions & 35 deletions src/unix/processx.c
Original file line number Diff line number Diff line change
Expand Up @@ -695,12 +695,41 @@ void processx__collect_exit_status(SEXP status, int retval, int wstat) {
}
}

typedef struct {
processx_handle_t *handle;
sigset_t old_mask;
int active;
} processx__wait_cleanup_t;

static void processx__wait_finish(processx__wait_cleanup_t *data) {
if (!data || !data->active) return;
data->active = 0;

/* Called from cleancall exit handlers too, so use sigprocmask() directly
rather than throwing helpers (exit handlers must not jump). */
if (data->handle->waitpipe[0] >= 0) {
/* Block SIGCHLD while closing and resetting waitpipe so
processx__sigchld_callback() cannot race on waitpipe[1]. */
sigset_t block;
sigemptyset(&block);
sigaddset(&block, SIGCHLD);
sigprocmask(SIG_BLOCK, &block, NULL);

close(data->handle->waitpipe[0]);
data->handle->waitpipe[0] = -1;
if (data->handle->waitpipe[1] >= 0) {
close(data->handle->waitpipe[1]);
data->handle->waitpipe[1] = -1;
}
}

sigprocmask(SIG_SETMASK, &data->old_mask, NULL);
}

static void processx__wait_cleanup(void *ptr) {
int *fds = (int*) ptr;
if (!fds) return;
if (fds[0] >= 0) close(fds[0]);
if (fds[1] >= 0) close(fds[1]);
free(fds);
processx__wait_cleanup_t *data = (processx__wait_cleanup_t *) ptr;
processx__wait_finish(data);
free(data);
}

/* In general we need to worry about three asynchronous processes here:
Expand Down Expand Up @@ -748,38 +777,35 @@ int c_processx_wait(processx_handle_t *handle, int timeout, const char *name) {
pid_t pid;
int timeleft = timeout;

int *fds = malloc(sizeof(int) * 2);
if (!fds) R_THROW_SYSTEM_ERROR("Allocating memory when waiting");
fds[0] = fds[1] = -1;
r_call_on_exit(processx__wait_cleanup, fds);

sigset_t old;
processx__block_sigchld_save(&old);

if (!handle) {
processx__procmask_set(&old);
return 1;
}

processx__wait_cleanup_t *cleanup_data =
malloc(sizeof(processx__wait_cleanup_t));
if (!cleanup_data) R_THROW_SYSTEM_ERROR("Allocating memory when waiting");
cleanup_data->handle = handle;
cleanup_data->active = 0;
r_call_on_exit(processx__wait_cleanup, cleanup_data);

processx__block_sigchld_save(&cleanup_data->old_mask);
cleanup_data->active = 1;

pid = handle->pid;

/* If we already have the status, then return now. */
if (handle->collected) {
processx__procmask_set(&old);
return 1;
ret = 1;
goto cleanup;
}

/* Make sure this is active, in case another package replaced it... */
processx__setup_sigchld();
processx__block_sigchld();

/* Setup the self-pipe that we can poll */
if (pipe(handle->waitpipe)) {
processx__procmask_set(&old);
R_THROW_SYSTEM_ERROR("processx error when waiting for '%s'", name);
}
fds[0] = handle->waitpipe[0];
fds[1] = handle->waitpipe[1];
processx__nonblock_fcntl(handle->waitpipe[0], 1);
processx__nonblock_fcntl(handle->waitpipe[1], 1);

Expand All @@ -790,8 +816,6 @@ int c_processx_wait(processx_handle_t *handle, int timeout, const char *name) {

processx__unblock_sigchld();



while (timeout < 0 || timeleft > PROCESSX_INTERRUPT_INTERVAL) {
do {
ret = poll(&fd, 1, PROCESSX_INTERRUPT_INTERVAL);
Expand Down Expand Up @@ -828,12 +852,7 @@ int c_processx_wait(processx_handle_t *handle, int timeout, const char *name) {
}

cleanup:
/* pipe is closed in the on_exit handler */
handle->waitpipe[0] = -1;
handle->waitpipe[1] = -1;

processx__procmask_set(&old);

processx__wait_finish(cleanup_data);
return ret != 0;
}

Expand Down Expand Up @@ -1048,7 +1067,8 @@ int c_processx_kill(SEXP status, double grace, SEXP name) {
pid_t pid;
int wstat, wp, result = 0;

processx__block_sigchld();
sigset_t old;
processx__block_sigchld_save(&old);

if (!handle) { goto cleanup; }

Expand All @@ -1070,8 +1090,9 @@ int c_processx_kill(SEXP status, double grace, SEXP name) {

/* Some other error? */
if (wp == -1) {
processx__unblock_sigchld();
R_THROW_SYSTEM_ERROR("processx_kill for '%s'", cname);
int err = errno;
processx__procmask_set(&old);
R_THROW_SYSTEM_ERROR_CODE(err, "processx_kill for '%s'", cname);
}

/* If the process is not running, return (FALSE) */
Expand All @@ -1084,14 +1105,18 @@ int c_processx_kill(SEXP status, double grace, SEXP name) {
int ret = kill(-pid, SIG); \
if (ret == -1 && (errno == ESRCH || errno == EPERM)) { goto cleanup; } \
if (ret == -1) { \
processx__unblock_sigchld(); \
R_THROW_SYSTEM_ERROR("process_kill for '%s'", cname); \
int err = errno; \
processx__procmask_set(&old); \
R_THROW_SYSTEM_ERROR_CODE(err, "process_kill for '%s'", cname); \
} \
} while(0)

if (grace_ms) {
KILL_WITH(SIGTERM);
if (c_processx_wait(handle, grace_ms, cname)) {
processx__procmask_set(&old);
int exited = c_processx_wait(handle, grace_ms, cname);
processx__block_sigchld();
if (exited || handle->collected) {
result = handle->exitcode == -SIGTERM;
goto cleanup;
}
Expand All @@ -1114,7 +1139,7 @@ int c_processx_kill(SEXP status, double grace, SEXP name) {
result = handle->exitcode == - SIGKILL;

cleanup:
processx__unblock_sigchld();
processx__procmask_set(&old);
return result;
}

Expand Down
146 changes: 146 additions & 0 deletions tests/testthat/test-wait.R
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,149 @@ test_that("no fd leak on unix", {
expect_equal(res$result$fd1, res$result$fd2)
expect_s3_class(res$result$err, "interrupt")
})

test_that("interrupted wait() does not close newly opened file descriptors", {
skip_on_os("windows")
skip_on_cran()
skip_if_not_installed("callr")
skip_if(is_valgrind())
skip_if(is_san())

rs <- callr::r_session$new()
withr::defer(rs$close())

ready <- withr::local_tempfile()
rs$call(
function(px_tool, ready) {
p <- processx::process$new(
px_tool,
c("sleep", "60"),
poll_connection = FALSE
)
on.exit(try(p$kill(), silent = TRUE), add = TRUE)
pid <- p$get_pid()

f1 <- tempfile()
f2 <- tempfile()
on.exit(unlink(c(f1, f2)), add = TRUE)
gc()

file.create(ready)
err <- tryCatch(p$wait(), interrupt = function(e) e)

c1 <- processx::conn_create_file(f1, read = FALSE, write = TRUE)
c2 <- processx::conn_create_file(f2, read = FALSE, write = TRUE)
on.exit(close(c1), add = TRUE)
on.exit(close(c2), add = TRUE)

tools::pskill(pid, tools::SIGKILL)
# process__exists() uses kill(pid, 0) without reaping zombies, so it
# becomes FALSE only after SIGCHLD itself has reaped the child.
deadline <- Sys.time() + 5
while (processx:::process__exists(pid) && Sys.time() < deadline) {
Sys.sleep(0.05)
}

list(
err = err,
reaped = !processx:::process__exists(pid),
w1 = processx::conn_write(c1, "ok"),
w2 = processx::conn_write(c2, "ok")
)
},
list(px_tool = get_tool("px"), ready = ready)
)

retry_until(function() file.exists(ready), interrupt = 0.02, timeout = 10)
Sys.sleep(0.1)
rs$interrupt()

deadline <- Sys.time() + 10
res <- NULL
while (is.null(res) && Sys.time() < deadline) {
if (rs$poll_process(500) == "ready") {
msg <- rs$read()
if (!is.null(msg) && msg$code != 301L) {
res <- msg
}
}
}

expect_false(is.null(res))
expect_null(res$error)
expect_s3_class(res$result$err, "interrupt")
expect_true(res$result$reaped)
expect_equal(res$result$w1, raw())
expect_equal(res$result$w2, raw())
})

test_that("interrupted kill() with grace restores signal handling", {
skip_on_os("windows")
skip_on_cran()
skip_if_not_installed("callr")
skip_if(is_valgrind())
skip_if(is_san())

rs <- callr::r_session$new()
withr::defer(rs$close())

ready <- withr::local_tempfile()
rs$call(
function(px_tool, ready) {
p <- processx::process$new(
px_tool,
c("sigterm", "ignore", "outln", "ready", "sleep", "60"),
stdout = "|",
poll_connection = FALSE
)
on.exit(try(p$kill(), silent = TRUE), add = TRUE)
pid <- p$get_pid()

deadline <- Sys.time() + 5
out <- character()
while (!("ready" %in% out) && Sys.time() < deadline) {
p$poll_io(500)
out <- c(out, p$read_output_lines())
}

file.create(ready)
err <- tryCatch(p$kill(grace = 60), interrupt = function(e) e)

tools::pskill(pid, tools::SIGKILL)
# process__exists() uses kill(pid, 0) without reaping zombies, so it
# becomes FALSE only if SIGCHLD is unblocked and reaped the child.
deadline <- Sys.time() + 5
while (processx:::process__exists(pid) && Sys.time() < deadline) {
Sys.sleep(0.05)
}

list(
ready = "ready" %in% out,
err = err,
reaped = !processx:::process__exists(pid)
)
},
list(px_tool = get_tool("px"), ready = ready)
)

retry_until(function() file.exists(ready), interrupt = 0.02, timeout = 10)
Sys.sleep(0.1)
rs$interrupt()

deadline <- Sys.time() + 10
res <- NULL
while (is.null(res) && Sys.time() < deadline) {
if (rs$poll_process(500) == "ready") {
msg <- rs$read()
if (!is.null(msg) && msg$code != 301L) {
res <- msg
}
}
}

expect_false(is.null(res))
expect_null(res$error)
expect_true(res$result$ready)
expect_s3_class(res$result$err, "interrupt")
expect_true(res$result$reaped)
})
Loading