How to get R to save its state when killed? - r

I would like to assign some code that will be run when R is killed, for instance, save(list=ls(),file="dump.RData"). I thought this would be by trapping signals, e.g. SIGTERM, as referred to in this post, but there's nothing about signals from the shell in ?conditions.
?conditions does mention user interrupts; you can e.g. catch a Ctrl-C with withCallingHandlers( Sys.sleep(10), interrupt=function (e){cat("I saw that.\n")} ), but this doesn't catch SIGTERM.
How can I do this?

Indeed if you send SIGUSR1 to an R process, it will dump the workspace and stop. On Linux you can do that with
kill -USR1 Rpid
where Rpid is the process id of the R instance you want to stop. You can find it with pgrep for instance.
If R is running in a terminal, you can interrupt it with CTRL-Z and then type
kill -USR1 %

Related

How to terminate (SIGINT) a subprocess in Haskell?

I'm writing a small program in Haskell which manipulates the commands arecordmidi and aplaymidi to record short improvisations on my digital piano through MIDI. I will press the R key, my program will create a new subprocess with the command arecordmidi. When I press R again, I want my recording to stop, by terminating the command arecordmidi.
How do I terminate the arecordmidi subprocess? If in a shell, CTRL+C would stop recording. This is what I want.
I'm using the following code to create the subprocess:
import System.Process
main = do
let rec_command = "arecordmidi -p \"CASIO USB-MIDI\" myRecording.midi"
process <- createProcess (shell rec_command)
-- I could try the following code, but the documentation of System.Process
-- says it's bad to use terminateProcess:
let (_, _, _, processHandle) = process
terminateProcess processHandle
terminateProcess sends a SIGTERM (terminate) signal to the process, which corresponds to the default behavior of the unix command kill, which generally is not what you want when trying to end a process nicely.
Ctrl+C sends the signal SIGINT (interrupt), which many applications handle by an orderly shutdown, and in your case probably results in the arecordmidi process saving outstanding data, and closing any pipes and files.
Looks like the way to send SIGINT with System.Process is with interruptProcessGroupOf.

Weird delay when using "tail -f" command

To monitor a log file I have to connect to an ssh connection and redirect the output of the log file(let's call it RemoteLog.txt) out to a local machine so it can be read by a java program and put on a GUI.
Right now I have the output redirected out of the ssh connection and onto the local machine with the command:
ssh remote#ip.address tail logs/RemoteLog.txt -f > ~/Log/LocalLog.txt
and everything works fine technically with one exception: for some reason LocalLog.txt only gets updated with the changes to RemoteLog.txt every 35 seconds to the millisecond.
It doesn't matter the number of changes to RemoteLog, the number of lines specified with the tail command, or using the >> operator vs the > operator; there is always a 35 second delay between updates of LocalLog.txt while RemoteLog is constantly updating.
Does anyone have any clue why this might be?

How can I shut down Rserve gracefully?

I have tried many options both in Mac and in Ubuntu.
I read the Rserve documentation
http://rforge.net/Rserve/doc.html
and that for the Rserve and RSclient packages:
http://cran.r-project.org/web/packages/RSclient/RSclient.pdf
http://cran.r-project.org/web/packages/Rserve/Rserve.pdf
I cannot figure out what is the correct workflow for opening/closing a connection within Rserve and for shutting down Rserve 'gracefully'.
For example, in Ubuntu, I installed R from source with the ./config --enable-R-shlib (following the Rserve documentation) and also added the 'control enable' line in /etc/Rserve.conf.
In an Ubuntu terminal:
library(Rserve)
library(RSclient)
Rserve()
c<-RS.connect()
c ## this is an Rserve QAP1 connection
## Trying to shutdown the server
RSshutdown(c)
Error in writeBin(as.integer....): invalid connection
RS.server.shutdown(c)
Error in RS.server.shutdown(c): command failed with satus code 0x4e: no control line present (control commands disabled or server shutdown)
I can, however, CLOSE the connection:
RS.close(c)
>NULL
c ## Closed Rserve connection
After closing the connection, I also tried the options (also tried with argument 'c', even though the connection is closed):
RS.server.shutdown()
RSshutdown()
So, my questions are:
1- How can I close Rserve gracefully?
2- Can Rserve be used without RSclient?
I also looked at
How to Shutdown Rserve(), running in DEBUG
but the question refers to the debug mode and is also unresolved. (I don't have enough reputation to comment/ask whether the shutdown works in the non-debug mode).
Also looked at:
how to connect to Rserve with an R client
Thanks so much!
Load Rserve and RSclient packages, then connect to the instances.
> library(Rserve)
> library(RSclient)
> Rserve(port = 6311, debug = FALSE)
> Rserve(port = 6312, debug = TRUE)
Starting Rserve...
"C:\..\Rserve.exe" --RS-port 6311
Starting Rserve...
"C:\..\Rserve_d.exe" --RS-port 6312
> rsc <- RSconnect(port = 6311)
> rscd <- RSconnect(port = 6312)
Looks like they're running...
> system('tasklist /FI "IMAGENAME eq Rserve.exe"')
> system('tasklist /FI "IMAGENAME eq Rserve_d.exe"')
Image Name PID Session Name Session# Mem Usage
========================= ======== ================ =========== ============
Rserve.exe 8600 Console 1 39,312 K
Rserve_d.exe 12652 Console 1 39,324 K
Let's shut 'em down.
> RSshutdown(rsc)
> RSshutdown(rscd)
And they're gone...
> system('tasklist /FI "IMAGENAME eq Rserve.exe"')
> system('tasklist /FI "IMAGENAME eq Rserve_d.exe"')
INFO: No tasks are running which match the specified criteria.
Rserve can be used w/o RSclient by starting it with args and/or a config script. Then you can connect to it from some other program (like Tableau) or with your own code. RSclient provides a way to pass commands/data to Rserve from an instance of R.
Hope this helps :)
On a Windows system, if you want to close an RServe instance, you can use the system function in R to close it down.
For example in R:
library(Rserve)
Rserve() # run without any arguments or ports specified
system('tasklist /FI "IMAGENAME eq Rserve.exe"') # run this to see RServe instances and their PIDs
system('TASKKILL /PID {yourPID} /F') # run this to kill off the RServe instance with your selected PID
If you have closed your RServe instance with that PID correctly, the following message will appear:
SUCCESS: The process with PID xxxx has been terminated.
You can check the RServe instance has been closed down by entering
system('tasklist /FI "IMAGENAME eq Rserve.exe"')
again. If there are no RServe instances running any more, you will get the message
INFO: No tasks are running which match the specified criteria.
More help and info on this topic can be seen in this related question.
Note that the 'RSClient' approach mentioned in an earlier answer is tidier and easier than this one, but I put it forward anyway for those who start RServe without knowing how to stop it.
If you are not able to shut it down within R, run the codes below to kill it in terminal. These codes work on Mac.
$ ps ax | grep Rserve # get active Rserve sessions
You will see outputs like below. 29155 is job id of the active Rserve session.
29155 /Users/userid/Library/R/3.5/library/Rserve/libs/Rserve
38562 0:00.00 grep Rserve
Then run
$ kill 29155

QProcess Killed or Successfully finished

How can I know if a Qprocess has successfully finished its execution or has been killed forcefully using process.kill()? In both the case the exitstatus() is normalExit.
Is there any way?
I don't think there's any specific function call, if that's what you're looking for. You didn't mention what platform you're using, but in the case of Linux, calling kill() sends a message to the process for it to terminate, so as far as the Process is concerned, everything is ok when it finished.
What you may be able to do though is subclass QProcess and overload the kill function to set a boolean value which you can check when the QProcess emits finished().
QProcesss::exiStatus() will give you this information. If the QProcess exits normally it will return Normal Exit or if the process was killed it will return Crash Status.
You can also check the QProcess::exitCode() to see the exact exit code for that process.
The following is a Linux example if a process is killed with SIGKILL.
QProcess subproc;
// Run the process here
subproc.waitForExit();
qDebug() << "Status: " << subproc.exitStatus()
qDebug() << "Code: " << subproc.exitCode()
While the sub-process is running run the following Linux command:
kill -9 <subproc PID>
Then the following is printed:
Status: CrashExit
Code: 9
Without using the kill command on the sub-process the following is output is observed:
Status: NormalExit
Code: 0

Monit fails to execute the complete command in start program

I'm using monit 5.4 on Mac 10.7.4 machine. When i tried to execute a example configuration
check process syslogd with pidfile /var/run/syslogd.pid
start program = "/etc/init.d/sysklogd start"
stop program = "/etc/init.d/sysklogd stop"
if 5 restarts within 5 cycles then timeout
from monit wiki page, I get the following error.
'syslogd' process is not running
'syslogd' trying to restart
'syslogd' start: /etc/init.d/sysklogd
'syslogd' failed to start
Monit does not take the complete command given in the "start program" of the monitrc file. It just takes the first word in the command and tries to execute it and fails. Is this a known issue? If yes, does it have a workaround? If not, what am i missing here and how to get it working?
Thanks in advance.
Try this (from http://mmonit.com/wiki/Monit/FAQ#execution)
start program = "/bin/bash -c '/etc/init.d/blah start'"
Does /etc/init.d/sysklogd actually exist?
On 10.8 I have /etc/init.d/syslog and manually running /etc/init.d/syslog restart works fine.

Resources