C library function - kill()
Description
kill The function is one of the functions in the C standard library, used to send a signal to a specified process or process group. It is defined in the header file, and allows a program to send signals to other processes to affect their behavior.
Declaration
Here is the declaration of the kill() function.
int kill(pid_t pid, int sig);
Parameters
pid_t pid: the process ID (PID) of the target process to which the signal is sent.- If both the
pid > 0, the signalsigwill be sent to the process whose process ID equalspidthe specified process. - If both the
pid == 0, the signalsigwill be sent to all processes that belong to the same process group as the calling process. - If both the
pid < -1, the signalsigwill be sent to all processes whose process group ID equalspidthe given group ID. - If both the
pid == -1, the signalsigwill be sent to all processes for which the caller has permission to send signals (except the process with process ID 1).
int sig: the number of the signal to send. Common signals includeSIGINT,SIGTERM,SIGKILL, etc.
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 use the kill function to send a SIGUSR1 signal to another process:
Example
#include
#include
#include
int
main
(
)
{
pid_t pid
=
getpid
(
)
;
// Get the process ID of the current process
// Send the 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].
C Standard Library -