4

I have a long running process (written in Java) that I wish to run asynchronously with system(..., wait=FALSE). In order to be able to determine when the process has ended i want to create a file afterwards as per the suggestions given in How to determine when a process started with system(..., wait=FALSE) has ended. The problem is that it seems the wait parameter only applies to the last line in a multiline system command, and I can't seem to find a way around that.

Example:

system('sleep 2')                 # waits 2 seconds before control is returned to the user
system('sleep 2', wait=FALSE)     # control is returned immediately
system('sleep 2; ls', wait=FALSE) # waits 2 seconds before control is returned to the user

I'm running on a mac system btw...

Community
  • 1
  • 1
ThomasP85
  • 1,624
  • 2
  • 15
  • 26

1 Answers1

6

I find strange that R's system only waits for the first command (it should be calling the shell, which then waits for both commands) but using && should do it:

system('sleep 2 && ls', wait=FALSE)

If R is appending a & to the command line, it becomes sleep 2; ls & and there the & affects only the second parameter.

Another solution would be to put brackets around the commands, ( sleep 2 ; ls ) & will perform both actions sequentially:

system('( sleep 2 ; ls )', wait=FALSE)
Ángel
  • 890
  • 7
  • 12
  • 1
    I'm also baffled by this, especially since the documentation states that it is appending '&' to the call in order to support wait. Doing this in the terminal with multiline command works fine..? Anyway, your approach works. – ThomasP85 Jun 17 '14 at 07:04
  • That explains its weird behavior, I have extended the answer with that. – Ángel Jun 17 '14 at 08:54
  • It is easy to confirm that R is just appending & to the command, look at the code for system... `if (!wait && !intern) command <- paste(command, "&")` – russellpierce Dec 18 '15 at 14:19
  • Notably this results in inconsistent behavior between Linux-alikes and Windows; which seems to be a running story for system (unsurprisingly). – russellpierce Dec 18 '15 at 14:24
  • 1
    @rpierce I agree, it's quite sad. It boils down to their use of different shells. Although in this case I should note you don't have `sleep` nor `ls` on windows. :) – Ángel Dec 21 '15 at 11:50