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!

2
  • 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. Commented Feb 29, 2016 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. Commented Feb 29, 2016 at 18:12

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this answer which does exactly what I was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.