Background:
Perl was created as a language for system scripts, so signal management (SIGTERM, SIGINT, SIGHUP) has always been a built-in and powerful feature. This system allows intercepting external events (user stop, daemon restart, timeouts) and properly concluding or altering the behavior of scripts.
Problem:
Incorrect signal handling is a common cause of improper termination or hanging of scripts, data loss during crashes, and the inability to restart processes without losing state or resources.
Solution:
Signals are handled by setting up handlers in a special hash %SIG. A good practice is to minimize actions inside the signal handler (e.g., setting a flag and safely exiting in the main thread). For proper functioning in threads and during multiple signal handling, specialized modules (e.g., POSIX::sigaction) are used.
Example:
my $term = 0; $SIG{TERM} = sub { $term = 1; }; while (1) { last if $term; # main work } print "Graceful shutdown ";
Key Features:
Can you use print/IO inside a signal handler?
Answer: Not recommended — it will result in incorrect operation and potential data loss! The modern standard is minimal code (only setting flags/clearing variables).
What happens if the signal handler is not reset after the first triggering?
Answer: The handler will run multiple times if the signal is received repeatedly. If a reaction is required only on the first event, the handler should reset $SIG{...} itself or send signals to itself.
Is signal handling thread-safe in Perl?
Answer: No! In multithreaded Perl, signal handlers are called only in the main thread (main interpreter); signals may be completely missed or incorrectly handled within threads.
A daemon process immediately calls close on all file descriptors and deletes temporary files in the handler upon receiving SIGTERM — occasionally, files are not deleted, data is lost.
Pros:
Cons:
The SIGTERM signal handler sets only the $exit variable, after which the main loop carefully finishes work, closes files, and only then frees resources.
Pros:
Cons: