Skip to content

stop R mainloop without calling exit(1)

2 messages · Thomas Kelder, Brian Ripley

#
Hello,

I'm trying to make my Java application work with R, which involves
sending and retrieving data and to run R functions from within the
Java application. I also need to have "live interaction" with R, to
show the R console output (e.g. warnings and print) and to enable the
user to enter input when a function asks for it.

Therefore I created a simple R console in Java using JRI
(http://rosuda.org/JRI/), and it works ok. The only problem is that I
have to start the R main loop which doesn't return. The only way to
stop it is to give R the quit command ('q()'), but then 'exit(1)' is
called from the R code and the Java Virtual Machine (including my
application) also shuts down.

My quick solution to this problem was to modify the R source code so
that the main loop ends without the need to call exit. The 'do_quit'
method in main.c now returns NULL instead of calling exit(1) and
'Rf_ReplIteration' checks for a returned NULL after each eval() and
breaks the main loop by returning -1.

Here are the simple changes to the R source code ('+' are the lines I
added, '//' are the lines I removed):

src/main/main.c : Rf_ReplIteration(...):
------------------------------------------------------------------
value = eval(R_CurrentExpr, rho);
+if(value == NULL)
+return(-1);

src/main/main.c : do_quit():
-------------------------------------
//exit(0);
+return(NULL)

I also removed the call to exit in src/linux/sys-std.c:Rstd_CleanUp
and src/gnuwin32/system.c:R_CleanUp for linux and windows
respectively.

This is obviously a quick hack to make it work (but it works fine,
also the standalone R exits ok this way), but I can imagine more
people want to use the mainloop with the possibility to return from it
without making their application to exit too. I wonder if it's
possible to include this possibility in future versions of R. Or do I
see this wrong and are there other (easier) solutions to achieve what
I want? Thanks in advance for your comments/reactions.

Thomas
#
This is already covered in the R-devel version of R: please consult
`Writing R Extensions' in that version.
On Thu, 31 Aug 2006, Thomas Kelder wrote:

            
But that's not true.  The documented way is

setup_Rmainloop
run a loop (which can return)
end_Rmainloop

The problem was that the only documented way to shut R down cleanly was 
end_Rmainloop (which did call exit), whereas there now is Rf_endEmbeddedR.
That's because you called end_Rmainloop, possibly by calling 
run_Rmainloop rather than taking control of the loop.

It seems that almost all users of embedded R did not call end_Rmainloop, 
and I met this when creating a common embedding interface for Unix and 
Windows versions of R: the Windows widgets (such as the graphics device) 
do need to be told to shut down.

[...]