📜 ⬆️ ⬇️

How to safely deliver SIGINT to the main thread?

Commentator AnotherMatt wonders why Win32 console applications deliver messages to another thread. Why don't they send them to the main thread?

Actually, I have a reverse question. Why is a UNIX signal sent to the main thread? This makes it almost impossible to do anything important inside a signal handler . The main stream may be inside the heap manager (hold the critical section) while receiving a signal. If the signal handler tries to access the heap, it will interlock with itself if you are lucky. In the worst case, a bunch will be damaged.

For example, consider this handler:

void catch_int(int sig_num)
{
/* catch_int */
signal(SIGINT, catch_int);

/* */
printf(" ");
fflush(stdout);
}

What happens if the signal is sent when the program executes its fflush (), say, after half the buffer has already been written? If two threads call fflush (), the second caller will wait for the end of the first. But here everything happens in the same flow; The second caller cannot wait for the first, since the first cannot work until the second returns a value!
')
(Note also that this handler potentially modifies the errno variable, which can lead to "impossible" errors in the main program.)

Win32 does not believe in the asynchronous interruption of a user mode code by another user code, because this makes it impossible to determine the status of a process. Delivering a signal to the second stream means that if the second stream tries to access the heap while the first thread owns it, the second stream will meekly wait for the stable state of the heap and only after its release will it start working with it.


UPD : Thank you all for your karma. moved to a specialized blog.

Source: https://habr.com/ru/post/41200/


All Articles