Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)
closed by

From here, I found that when a sign/signal is gotten, exit_gracefully is called in the meantime the code inside while True is running. From the start, I imagined that handler is running in another string so I worked a code to test it out: 

import os

import signal

import threading

def sig_handler(signal_frame, num):

    print('handler PID: {}'.format(os.getpid()))

    print('current thread identity: {}'.format(threading.current_thread().ident))

signal.signal(signal.SIGTERM, sig_handler)

try:

    print('main execution PID: {}'.format(os.getpid()))

    print('current thread identity: {}'.format(threading.current_thread().ident))

    while True:

        time.sleep(5)

        print('Hello')

except KeyboardInterrupt:

    print('Good bye')

I ran the code and first conveyed a SIGTERM message (utilizing kill- SIGTERM pid command) and afterward conveyed a SIGINT message. The yield was:

main execution PID: 1002

current thread identity: 140284238558976

Hello

Hello

handler PID: 1002

current thread identity: 140284238558976

Hello

Hello

Good bye

You see that everything is something similar, yet how it's conceivable that the handler running in the very definite setting that principle code is executing? Shouldn't be in another thread?

closed

4 Answers

0 votes
by (15.4k points)
 
Best answer

In the given code, the signal handler (sig_handler) is executed within the context of the main thread. It may seem like the handler is running in a separate thread, but in Python, signal handlers are invoked within the main thread itself. When a signal is received, the main thread temporarily pauses its ongoing execution and calls the signal handler. Once the handler completes its execution, the main thread resumes from where it left off. Consequently, you observe that the output of the signal handler (handler PID and current thread identity) appears within the same thread and process as the main execution.

It is crucial to understand that Python's signal handling is not inherently multi-threaded. To handle signals in a separate thread, you need to explicitly create a dedicated thread and assign it the task of signal handling using the signal.set_wakeup_fd() function.

In the provided code, since the signal handler executes within the main thread, it shares the same process ID (os.getpid()) and thread identity (threading.current_thread().ident) as the main execution.

To summarize, in your code snippet, the signal handler operates within the main thread and process, rather than in a distinct thread.

0 votes
by (26.4k points)

Check the documentation for answer:

Python signal handlers are always executed in the main Python thread, even if the signal was received in another thread.

Also:

the low-level signal handler sets a flag which tells the virtual machine to execute the corresponding Python signal handler at a later point

So when a sign/signal is gotten, the overseer doesn't execute close by the code in the while loop. All things being equal, the virtual machine executing your code is advised to run the sign taking care of code 'soon', which could be after X number of bytecode guidelines, so basically your loop goes on stop while the controller code is running. Changing your code a little shows this:

def sig_handler(signal_frame, num):

    print('handler PID: {}'.format(os.getpid()))

    print('current thread identity: {}'.format(threading.current_thread().ident))

    time.sleep(5) # we put a long delay here

signal.signal(signal.SIGTERM, sig_handler)

try:

    print('main execution PID: {}'.format(os.getpid()))

    print('current thread identity: {}'.format(threading.current_thread().ident))

    while True:

        time.sleep(1) # sleep less now

        print('Hello')

except KeyboardInterrupt:

    print('Good bye')

Presently, when you send your SIGTERM, you'll notice the execution of your while loop stops for 5s.

Are you pretty much interested to learn python in detail? Come and join the python training course to gain more knowledge.

0 votes
by (25.7k points)
In the provided code, the signal handler (sig_handler) is executed within the main thread context. The misconception may arise from the assumption that the signal handler runs in a separate thread. However, in Python, signal handlers are executed within the main thread, interrupting the execution flow at the point where the signal is received.

When a signal is received, the main thread temporarily suspends its current execution and invokes the signal handler. Once the signal handler completes its execution, the main thread resumes from where it left off. This is why you see the signal handler output (handler PID and current thread identity) within the same thread and process as the main execution.

It's important to note that signal handling in Python is not multi-threaded by default. If you want to handle signals in a separate thread, you would need to explicitly create a separate thread and dedicate it to signal handling using the signal.set_wakeup_fd() function.

In your provided code, since the signal handler is executing within the main thread, it has access to the same process ID (os.getpid()) and thread identity (threading.current_thread().ident) as the main execution.

In summary, the signal handler in your code runs within the same thread and process as the main execution, not in a separate thread.
0 votes
by (19k points)

In the given code, the signal handler (sig_handler) is executed within the main thread context, not in a separate thread. Python's signal handling does not inherently involve multi-threading. Therefore, when a signal is received, the main thread temporarily pauses its execution and calls the signal handler. After the handler completes its execution, the main thread resumes from where it left off. As a result, the output of the signal handler appears within the same thread and process as the main execution.

Related questions

0 votes
1 answer
0 votes
4 answers
0 votes
1 answer
asked Jun 28, 2020 in Data Science by blackindya (18.4k points)
0 votes
1 answer
asked Dec 27, 2020 in Python by ashely (50.2k points)

Browse Categories

...