In base R, there are 3 main mechanisms for invoking a system command: system
, system2
, and shell
(which seems to share a manpage with system
). None of them provide a very reliable cross-platform way to run a system command without a shell getting in the way - and if a shell intervenes, we need to worry about shell injection attacks, about making sure the quoting is correct, and so on.
Some languages provide direct access to the C-level execvp
function (e.g. Perl's system PROGRAM LIST
mechanism), which is extremely helpful when I want to make sure that the strings in an array are exactly the strings the subprocess will see in its arguments, without looking around for the appropriate quoting routine for embedded whitespace, quotes, etc. and worrying about what they'll do on different platforms and different versions of shells.
Is there a similar no-shell system-call mechanism available in R, perhaps in a CRAN package somewhere? And/or is there any appetite for creating such a mechanism if there isn't one already?
The following code runs a command in R without shell interaction:
library(inline) cfun <- cfunction(sig = signature(), includes = "#include <unistd.h>", body = 'execl("/bin/date", "date", 0, 0, (char *)0);') cfun()
I'm pretty sure this is a bad idea, as I think it would terminate the R process upon completion of the executed process. What about fork?
The base package parallel C function mc_fork
use the C system command fork
to achieve this, with pipes for inter-process communication. I do not know how this would fly on Windows with MinGW, but since it is in a base package, it would seem likely to work, although perhaps with a very different downstream mechanism.
In the R sources for parallel
I see in R-devel/src/library/parallel/src/fork.c
SEXP mc_fork(SEXP sEstranged) ... pid = fork();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With