Search code examples
rsshnohup

Executing R script ssh and nohup


I have the R file test.R in a remote server. It contains only this:

Sys.sleep(5)

In my local machine I have my local.R file:

library(ssh)

host<-"root@someip"
keyfile<-"mykeyfile.osh"
passwd<-"mypassword"

ssh_session <- ssh::ssh_connect(host,keyfile,passwd)

print(Sys.time())
a<-ssh::ssh_exec_wait(ssh_session,
                      command = 'nohup R CMD BATCH test.R &')
print(Sys.time())

ssh::ssh_disconnect(ssh_session)

When I execute local.R, I have this output:

[1] "2023-09-16 17:41:52.707577 CEST"
[1] "2023-09-16 17:41:58.132833 CEST"

If you observe, the difference between both times is more than 5 seconds. What I expect is the second print not to wait till to finalize the execution of test.R. My final goal is to make it work from a shiny app.

EDIT. I also used command = 'nohup Rscript test.R &', but the result quite the same.

Any idea? Thanks!


Solution

  • As mentioned in the comments, ssh_exec_wait() always waits for the server-side standard output and error streams to be closed. Incidentally, this is the same behaviour as that of the ssh command line utility unless pseudo-terminal allocation via the -t option is forced.

    One option to avoid the wait is therefore to redirect the command’s output and error streams to detach them from the terminal:

    a <- ssh::ssh_exec_wait(
      ssh_session,
      command = 'nohup Rscript test.R >/dev/null 2>&1 &'
    )
    

    Beware that the above will (obviously) discard any output. If you need the output you either need to adjust your script, or alternatively perform redirection into a suitable file.