1. The basic concept of signal
A signal is an event generated by the system in response to a certain condition, and the process will perform the corresponding action upon receiving the signal.
2. The corresponding method of modifying the signal - signal()
Use signal() to modify the specified signal
Ignore the signal: SIG_IGN
Default processing: SIG_DFL
Custom: signal processing function written by yourself
Example 1:
For example, the following program shows that the SIGINT (the signal is generated when ctrl+c is pressed on the keyboard) signal is modified to a custom fun handler
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<assert.h>
void fun(int sign)
{
printf("fun was called, sign = %d\n", sign);
}
int main()
{
signal(SIGINT, fun);
while(1)
{
sleep(1);
printf("main running\n");
}
exit(0);
}
The program runs as follows:
3. Send a signal - kill()
kill() can send the specified signal to the specified process'
int kill(pid_t pid,int sig);
pid > 0 specifies which process to send the signal to
pid == 0 The signal is sent to a process in the same process group as the current process
pid == -1 sends the signal to all processes on the system that have permission to send
pid < -1 Send the signal to all processes whose process group id is equal to the absolute value of pid and has permission to send.
sig specifies the type of signal sent.
Example 2:
The following code means: run this program and enter the pid of a process, and use the sig signal to process the process
#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include <signal.h>
int main(int argc, char* argv[])//pid, sig
{
if ( argc != 3 )
{
printf("argc error\n");
exit(0);
}
int pid = 0;
int sig = 0;
sscanf(argv[1],"%d",&pid);
sscanf(argv[2],"%d",&sig);
if ( kill(pid,sig) == -1 )
{
perror("kill error");
}
exit(0);
}
The program runs as follows:
query the process id of example 1, then run example 2, kill process 14851 (example 1) with the SIGKILL (#define SIGKILL 9) signal