I replicated the following code from a python program to nim to create processes via fork. But how to do to kill all processes (parent and child's) at once?
import posix
import os
proc parent_child(p = 0) =
while true:
echo "Process: ", p
sleep(1000)
proc main() =
var children: seq[Pid]
let forks = 3
for f in 0 .. forks - 1:
let pid = fork()
if pid < 0:
# error forking a child
quit(QuitFailure)
elif pid > 0:
let p = getpid()
echo "In parent process: ", int(p)
children.add(pid)
else:
let p = getpid()
echo "In child process: ", int(p)
parent_child(f)
quit()
for child in children:
var status: cint
discard waitpid(child, status, 0)
main()
you can kill all processes that share a PGID with kill(-pgid,SIGTERM) or all processes that share the same PGID as the current process with kill(0,SIGTERM)
so kill(0, SIGTERM) (or kill(-1 * getpgid(0),SIGTERM) ) will kill the parent and all the children immediately, even if sent from a child process.
if you only want to kill the children but keep the parent running, you can kill them all individually:
for child in children:
kill(child,SIGTERM)
Thanks @shirleyquirk for your help, but my problem persists, or I haven't explained myself well. What I want is to write the command "kill" in the terminal to kill the process and all of its descendants.
How to catch the signal sent by "kill" in Nim?
Example:
# launch n processes
$ ./server
# how to kill parent and child's at once?
$ kill -9 pid
it is not possible to catch or ignore SIGKILL (-9) or SIGSTOP
@dom96 and @kaushalmodi have put together this example for other signal handlers: https://gist.github.com/dom96/908782