Signal processing mechanism is very important in Linux programming, it is similar to the interrupt system in MCU; When we write the interrupt function, we need to set the address of the interrupt function, set its corresponding register, so that we can jump to the interrupt function to execute correctly when the interrupt event occurs.
In Linux, the signal is similar to this, the general programming model is to define the interrupt function, and then register the interrupt function, so that the process receives a specific signal, you can jump to the signal processing function to execute;
1.kill function and raise function
The Kill function is used to send a signal to a process or process group;
--int Kill (pid_t pid, int signo);
The Raise function allows the process to send a signal to itself;
--int raise (int signo);
Call Raise (Signo); equivalent to Kill (Getpid (), signo);
Note: The first parameter of the KILL function:
Here is an example of using the Kill function:
#include <stdio.h> #include <stdlib.h> #include <signal.h>pid_t pid;void fun (int a) { if (a = = SIGABRT) printf ("Have fun!\n"); if (a = = SIGUSR1) { printf ("fuck!\n");} } void Send () { kill (PID, SIGUSR1);//Only send MSG to progress or progress group!} int main () { int cnt = 0; Signal (SIGABRT, fun); Signal (SIGUSR1, fun); PID = fork (); if (PID = = 0) { while (1) { printf ("child!\n"); Sleep (1); } } while (1) { printf ("father!\n"); cnt++; if (cnt = = 5) send (); Sleep (1);} }
2. Alarm function and Pause function
The alarm function is used to set a timer that, when timed out, produces a sigalrm signal that, by default, terminates the process that invokes the alarm function if the signal is not captured.
--unsigned int alarm (unsigned int seconds);
The pause function suspends the calling process until it snaps to a signal .
--int pause (void);
Instance:
#include <signal.h> #include <stdio.h>void fun (int id) { if (id = = SIGUSR1) { printf ("sigusr1\n "); } if (id = = SIGALRM) { printf ("sigalrm!\n");} } int main () { signal (SIGUSR1, fun); Signal (SIGALRM, fun); Alarm (5); If not catch, progress return; for (;;) Pause (); return 0;}
3. Signal Set
A set of signals that can contain multiple signals, the data type is sigset_t, and the corresponding signal set function is also available;
There are some of the following functions:
Linux system Programming _10_ signal