Reference book: Unxi Environment Advanced Programming
Signal function:
<span style= "Font-family:microsoft yahei;font-size:18px;" >typedef void (*sighandler_t) (int); sighandler_t signal (int signum, sighandler_t handler);</span>
The prototype is:
<span style= "Font-family:microsoft yahei;font-size:18px;" >void (*signal (int signum,void (*handler) (int))) (int);</span>
we generally use the first, that is, through the typedef rewrite.
Note: The signal function I generally consider to be the way that the kernel registers the processing of the current process to receive signals. signal (sigint,handler);
parameter Description:
Signum: Specify the signalHandler:sig_ign ignores this signal, SIG_DFL uses the system default to process the signal, the custom signal processing function pointer.
Understanding practical examples is the best way to learn:Example One:To make a child process a corpse by asynchronous means
Note: When a child process terminates, the parent process is SIGCHLD, and the default processing action of the signal is ignored, and the parent process can customize the handler function of the SIGCHLD signal so that the parent process only needs to concentrate on its own work, does not care about the child process, and notifies the parent process when the child process terminates. The parent process calls the wait cleanup child process in the signal handler function.
#include <stdio.h> #include <signal.h> #include <unistd.h> #include <stdlib.h>void child_exit_ Handler (int signum) { if (Signum = = SIGCHLD) { printf ("Child exit.\n"); Wait (NULL);} } int main () { int pid; int i = 0; Want kernel register, handle SIGCHLD signal way signal (sigchld,child_exit_handler); if (PID = fork ()) < 0) { perror ("Fail to Fork"); Exit (exit_failure); } else if (PID = = 0) {for (i = 0;i < 5;i + +) { printf ("Child loop.\n"); Sleep (1); } } else{for (i = 0;i < 5;i + +) { printf ("Father loop.\n"); Sleep (2); } } Exit (exit_success);}
The results of the operation are as follows:[Email protected] test]$gcc test.c
[[email protected] test]$ ls
A.out test.c
[Email protected] test]$ ./a.out
Child Loop.
Father Loop.
Child Loop.
Father Loop.
Child Loop.
Child Loop.
Father Loop.
Child Loop.
Child exit.
Father Loop.
Father Loop.
[Email protected] test]$
-----signal signal for advanced programming in the UNIX environment