1. kill() 函数
进程通过调用kill发送信号给其他进程(包括他们自己)
#include <sys/types.h>
#include <signal.h>
int kill(pid_t pid, int sig);
成功返回0,错误返回-1.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <signal.h>
int main(int argc, char *argv[]) {
int pid;
if (2 > argc)
exit(-1);
pid = atoi(argv[1]);
printf("pid: %d\n", pid);
if (-1 == kill(pid, SIGINT)) {
perror("kill error");
exit(-1);
}
exit(0);
}
以上代码,向进程发送SIGINT信号,终止进程。
2. alarm() 函数
调用alarm函数向自己发送SIGALRM信号,alarm函数安排内核在secs秒后发送一个SIGALRM信号给调用进程。
#include <unistd.h>
unsigned int alarm(unsigned int seconds);
使用alarm设计一个闹钟:
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
static void sig_handler(int sig) {
puts("Alarm timeout");
exit(0);
}
int main(int argc, char *argv[]) {
struct sigaction sig = {0};
int second;
if (2 > argc)
exit(-1);
sig.sa_handler = sig_handler;
sig.sa_flags = 0;
if (-1 == sigaction(SIGALRM, &sig, NULL)) {
perror("sigaction error");
exit(-1);
}
second = atoi(argv[1]);
printf("定时时长:%d秒\n", second);
alarm(second);
for (;;)
sleep(1);
exit(0);
}