Manually Stop Jupyter Kernel and Prevent from Restarting

691 views Asked by At

Background

I have created a Jupyter kernel A from which I launch another kernel B. I am doing this in order to audit the execution of kernel B. So when a user selects kernel A from the interface, kernel B is launched in the background which then executes the notebook code. strace is being used to audit the execution. After the audit phase, code, data, and provenance etc. of the program execution are recorded and stored for analysis later on.

Problem

After the notebook program ends, I intend to stop tracing the execution of kernel B. This does not happen unless I stop the execution of kernel B launched internally by kernel A. The only way I have been able to do this is using the kill command as such:

os.kill(os.getpid(), 9)

This does the job but with a side-effect: Jupyter restarts the kernel automatically which means kernel A and B are launched and start auditing the execution again. This causes certain race conditions and overwrites of some files which I want to avoid.

Possible Solution

To my mind, there are two things I can do to resolve this issue:

  1. Exit the kernel B program gracefully so the auditing of the notebook code gets completed and stored. This does not happen with the kill command so would need some other solution
  2. Avoid automatic restart of the kernel, with or without the kill command.

I have looked into different ways to achieve the above two but have not been successful yet. Any advice on achieving either of the above two solutions would be appreciated, or perhaps another way of solving the problem.

1

There are 1 answers

3
geekay On

have you tried terminating kernel B instead of killing it using 15 instead of 9

os.kill(os.getpid(), signal.SIGTERM)  
#or  
os.kill(os.getpid(), 15)

other values for kill are signal.SIGSTOP=23 , signal.SIGHUP=1

Other option could be to insert following code snippet on top of the code

import signal
import sys
def onSigExit():
    sys.exit(0)
    #os._exit(0)
signal.signal(signal.SIGINT, onSigExit)
signal.signal(signal.SIGTERM, onSigExit)

now you should be able to send

os.kill(os.getpid(),15)

and it should exit gracefully and not restart