Hello
I want to create a "wrapper" application in Nim, which will launch another process, and if this process exits, it needs to relaunch it. But of course I want to be able to terminate this procedure.
In my mind I thought this would be easy:
and I was expecting when I press CTRL+C either the hook (due to quit) to exit, but even if not, the boolean flag to stop the loop.
But I am so wrong. It seems like CTRL+C is just passed to the child process, which is restarted and the loop restarts it.
So I am stuck. Any way I can do this?
To answer my own question, and maybe to help future people on this forum.
It seems that with execCmd this is not possible. My guess is, since it is forwarding the standard input to the child process, this also forwards the "break" event.
I managed to solve this using a different approach. I am using startProcess (but I tested it with execProcess too) and make sure not to forward the input to the child process (the default behavior). Then the system behaved exactly as I was expecting.
On non-MS Windows OS, execCmd proc in osproc module is implemented with system function in stdlib.h in C languege.
(Open https://github.com/nim-lang/Nim/blob/devel/lib/pure/osproc.nim, and grep "proc execCmd(" and search for 2nd one)
Acoording to this document, https://man7.org/linux/man-pages/man3/system.3.html
During execution of the command, SIGCHLD will be blocked, and SIGINT and SIGQUIT will be ignored, in the process that calls system(). (These signals will be handled according to their defaults inside the child process that executes command.)
startprocess proc uses lower level functions to run external process so SIGINT is not ignored. A hook set by setControlCHook can be called even if you call startProcess with poParentStreams option.
import std/osproc
proc hook() {.noconv.} =
echo "hook was called"
setControlCHook(hook)
echo "Run child"
let ret = execCmd("./test")
# Pushing Ctrl + c doesn't call hook
echo ret
echo "End child"
echo "Run startProcess"
var p = startProcess("test",options = {poParentStreams})
echo p.waitForExit()
# Pushing Ctrl + c calls hook
p.close()
echo "End startProcess"