[Rd] Detecting whether a process exists or not by its PID?

Gábor Csárdi c@@rdi@g@bor @ending from gm@il@com
Fri Aug 31 08:14:18 CEST 2018

On Fri, Aug 31, 2018 at 1:18 AM Henrik Bengtsson
<henrik.bengtsson using gmail.com> wrote:
>   pid_exists <- function(pid) as.logical(tools::pskill(pid, signal = 0L))
> returns TRUE for existing processes and FALSE otherwise, but I'm not
> sure if I can trust this.  It's not a documented feature in
> ?tools::pskill, which also warns about 'signal' not being standardized
> across OSes.

Yes, as long as tools::pskill() is willing to call a killl(0) system
call, AFAIK this will work fine on all UNIX systems.

> The other Linux alternative I can imagine is:
>   pid_exists <- function(pid) system2("ps", args = c("--pid", pid),
> stdout = FALSE) == 0L
> Can I expect this to work on macOS as well?  What about other *nix systems?

There is no --pid option on macOS. I think simply `ps <pid>` is
better, but some very minimal systems might not have ps at all.

> And, finally, what can be done on Windows?

You need to call OpenProcess from C, or find some base R function that
does that without messing up the process. Seems like tools::psnice()
does that.

> I'm sure there are packages on CRAN that provides this, but I'd like
> to keep dependencies at a minimum.

Yes, e.g. the ps package does this, and it does it properly, i.e. you
don't need to worry about pid reuse. Pid reuse does cause problems
quite frequently, especially on Windows, and especially on a system
that starts a lot of processes, like win-builder.


> I appreciate any feedback. Thxs,
> Henrik
> ______________________________________________
> R-devel using r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel

More information about the R-devel mailing list