Linux进程间通信Signal
前面一片中提到Linux信号中一些signal相关的用来发送信号的函数:
int kill(pid_t pid, int sig);
int raise(int sig);
int killpg(int pgrp, int sig);
我们在terminal
中常用的kill -9
等命令是使用上面的kill()
函数实现的.
需要注意的是, kill()
函数中的pid
参数根据不同的值有不同的含义, 可以man查看一下.
raise
函数给自己发送信号, 等价于kill(getpid(), sig);
alarm()
函数会在满足时间以后发送SIGALRM
信号
#include <unistd.h>
unsigned int alarm(unsigned int seconds);
abort()
函数使当前进程接收到SIGABRT
信号而异常终止。就像exit
函数一样,abort
函数总是会成功的,所以没有返回值。
#include <stdlib.h>
void abort(void);
定时器setitimer()
函数
#include <sys/time.h>
int setitimer(int which, const struct itimerval *value, struct itimerval *ovalue));
参数:
- which: 指定定时器类型
-
ITIMER_REAL
:经过指定的时间后,内核将发送SIGALRM
信号给本进程 -
ITIMER_VIRTUAL
:程序在用户空间执行指定的时间后,内核将发送SIGVTALRM信号给本进程 -
ITIMER_PROF
:进程在用户空间执行和内核空间执行时,时间计数都会减少,通常与ITIMER_VIRTUAL
共用,代表进程在用户空间与内核空间中运行指定时间后,内核将发送SIGPROF
信号给本进程
-
- value: 指定定时器触发的时间.
- ovalue: 获取原来定时器触发的时间, 一般传NULL
其中struct itimerval
内容是
struct itimerval{
struct timeval it_interval; /* next value */
struct timeval it_value; /* current value */
}
struct timeval {
long tv_sec; /* seconds */
long tv_usec; /* microseconds */
};
使用定时器的实例:
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
void handler(int sig) { printf("recv a sig=%d\n", sig); }
int main() {
sighandler_t ohandler = signal(SIGALRM, handler);
if (ohandler == SIG_ERR) {
perror("signal");
exit(1);
}
struct itimerval it = {{1, 0}, {5, 0}};
;
setitimer(ITIMER_REAL, &it, NULL);
for (;;) {
pause();
}
return 0;
}
网友评论