6

Can anyone suggest how I might get this working....

I have an R script that takes several minutes to run and writes a few hundred lines of output. I want to write a shell script wrapper around this R script which will launch the R script in the background, pipe its output to a file and start following the bottom of that file. If the user then enters CTRL-C I want that to kill the shell script and tail command but not the R script. Sounds simple right?

I've produced a simplified example below, but I don't understand why this doesn't work. Whenever I kill the shell script the R script is also killed despite apparently running in the background. I've tried nohup, disown etc with no success.

example.R

for(i in 1:1000){
   Sys.sleep(1)
   print(i)
}

wrapper.sh

#!/bin/bash

Rscript example.R > logfile &

tail -f logfile

Thanks in advance!

David
  • 63
  • 6
  • No, that's not it. If I do that I get two jobs running in the background and CNTL-C doen't kill either of them. I want CNTL-C to kill tail -f but not Rscript. – David Feb 29 '16 at 16:52
  • I don't have access to `R`, but I just tried this exact script with PHP and it works as described. Ctrl-C kills the parent script but leaves the background process running. – miken32 Feb 29 '16 at 18:12

1 Answers1

3

The following seems to work on my Ubuntu machine:

#!/bin/bash

setsid Rscript example.R > logfile.txt &

tail -f logfile.txt

Here are some of the relevant processes before sending SIGINT to wrapper.sh:

 5361 pts/10   00:00:00 bash
 6994 ?        00:00:02 update-notifier
 8519 pts/4    00:00:00 wrapper.sh
 8520 ?        00:00:00 R
 8521 pts/4    00:00:00 tail

and after Ctrl+C, you can see that R is still running, but wrapper.sh and tail have been killed:

 5361 pts/10   00:00:00 bash
 6994 ?        00:00:02 update-notifier
 8520 ?        00:00:00 R

Although appending your Rscript [...] command with & will send it to the background, it is still part of the same process group, and therefore receives SIGINT as well.


I'm not sure if it was your intention, but since you are calling tail -f, if not interrupted with Ctrl+c, your shell that is running wrapper.sh will continue to hang even after the R process completes. If you want to avoid this, the following should work,

#!/bin/bash

setsid Rscript example.R > logfile.txt &

tail --pid="$!" -f logfile.txt

where "$!" is the process id of the last background process executed (the Rscript [...] call).

nrussell
  • 18,382
  • 4
  • 47
  • 60