C library functions -kill()
C Standard Library - <signal.h>
Description
killThe function is a function in the C standard library used to send signals to a specified process or process group. It is defined in<signal.h>the header file, and allows a program to send signals to other processes to affect their behavior.
Declaration
Below is the declaration of the kill() function.
int kill(pid_t pid, int sig);
Parameter
pid_t pid: The process ID (PID) of the target process to which the signal is to be sent.- if
pid > 0, then the signalsigWill be sent to the process whose ID equalspidof the process. - if
pid == 0, then the signalsigWill be sent to all processes in the same process group as the calling process. - if
pid < -1, then the signalsigWill be sent to the process group whose ID equalspidof all processes. - if
pid == -1, then the signalsigWill be sent to all processes for which the caller has permission to send signals (except for the process with PID 1).
- if
int sig: The signal number to send. Common signals includeSIGINT、SIGTERM、SIGKILLetc.
Return Value
- Returns 0 on success.
- Returns -1 on failure, and sets
errnoto indicate the error type.
Example
The following is a simple example program demonstrating how to usekillThe function sends to another processSIGUSR1Signal:
Example
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
int main() {
pid_t pid = getpid(); // Get the process ID of the current process
// Send SIGUSR1 signal to the current process
if (kill(pid, SIGUSR1) == -1) {
perror("kill");
return 1;
}
printf("SIGUSR1 signal sent to process %d.\n", (int)pid);
return 0;
}
#include <signal.h>
#include <unistd.h>
int main() {
pid_t pid = getpid(); // Get the process ID of the current process
// Send SIGUSR1 signal to the current process
if (kill(pid, SIGUSR1) == -1) {
perror("kill");
return 1;
}
printf("SIGUSR1 signal sent to process %d.\n", (int)pid);
return 0;
}
After compiling and running the program, the output will be:
SIGUSR1 signal sent to process [进程ID].other extensions