您的位置:首页 > 运维架构 > Linux

Linux系统编程4.信号处理

2017-04-05 14:18 375 查看

1. 信号产生

Linux 下的信号可以类比于 DOS 下的 INT 或者是 Windows 下的事件。

在有一个信号发生的时候,相应的信号就会发送给相应的进程。

Linux 下的信号有以下几个. 使用 kill -l命令 可以得到以下的输出结果:

1) SIGHUP
2) SIGINT    //中断CTRL+C
3) SIGQUIT
4) SIGILL
5) SIGTRAP
6) SIGABRT
8) SIGFPE
9) SIGKILL
10) SIGUSR1
11) SIGSEGV
12) SIGUSR2
13) SIGPIPE
14) SIGALRM
15) SIGTERM
17) SIGCHLD
18) SIGCONT
19) SIGSTOP
20) SIGTSTP
21) SIGTTIN
23) SIGURG
24) SIGXCPU
25) SIGXFSZ
26) SIGVTALRM
27) SIGPROF
28) SIGWINCH
29) SIGIO
30) SIGPWR


信号事件的发生有两个来源:

1.是硬件的原因(比如我们按下了键盘),

2.是软件的原因(比如我们使用系统函数或者是命令发出信号).

最常用的四个发出信号的系统函数是 kill, raise, alarm 和 setitimer 函数。

#include <sys/types.h>;
#include <signal.h>;
#include <unistd.h>;
int kill(pid_t pid,int sig);
/*kill 系统调用负责向进程发送信号 sig.*/
/*
如果 pid 是正数,那么向信号 sig 被发送到进程 pid.
如果 pid 等于 0,那么信号 sig 被发送到所有和 pid 进程在同一个进程组的进程.
如果 pid 等于-1,那么信号发给所有的进程表中的进程,除了最大的哪个进程号.
如果 pid 由于-1,和 0 一样,只是发送进程组是-pid.
*/
//最多的是第一个情况

int raise(int sig);
/*raise 系统调用向自己发送一个 sig 信号.相当于kill(getpid(),sig)*/

unisigned int alarm(unsigned int seconds);
/*在 seconds 秒后向自己发送一个 SIGALRM 信号*/


#include <unistd.h>;
main()
{
unsigned int i;
alarm(1);
for(i=0;1;i++)
printf("I=%d",i);
}
/*SIGALRM的缺省操作是结束进程,所以程序在 1秒之后结束*/


2. 信号的操作

信号操作最常用的方法是信号屏蔽.信号屏蔽要用到下面的几个函数:

#include <signal.h>;
int sigemptyset(sigset_t *set);
/*初始化信号集合 set,将 set 设置为空*/
int sigfillset(sigset_t *set);
/*始化信号集合,只是将信号集合设置为所有信号的集合*/
int sigaddset(sigset_t *set,int signo);
/*将信号 signo 加入到信号集合之中*/
int sigdelset(sigset_t *set,int signo);
/*将信号从信号集合中删除*/
int sigismember(sigset_t *set,int signo);
/*查询信号是否在信号集合之中*/
int sigprocmask(int how,const sigset_t *set,sigset_t *oset);
/*最为关键的一个函数.在使用之前要先设置好信号集合 set.

这个函数的作用是将指定的信号集合 set 加入到进程的信号阻塞集合之中去,如果提供了 oset 那么当前的进程信号阻塞集合将会保存在 oset 里面.

参数 how 决定函数的操作方式:
SIG_BLOCK:增加一个信号集合到当前进程的阻塞集合之中.
SIG_UNBLOCK:从当前的阻塞集合之中删除一个信号集合.
SIG_SETMASK:将当前的信号集合设置为信号阻塞集合.
*/


实例:

#include <signal.h>;
#include <stdio.h>;
#include <math.h>;
#include <stdlib.h>;
int main(int argc,char **argv)
{
double y;
sigset_t intmask;  /*定义一个信号集intmask*/
int i,repeat_factor;
if(argc!=2)        /*参数错误*/
{
fprintf(stderr,"Usage: %s repeat_factor\n\a",argv[0]);
exit(1);
}
if((repeat_factor=atoi(argv[1]))<1)/*atoi将字符串转换成int*/
repeat_factor=10;
sigemptyset(&intmask); /* 将信号集合设置为空 */
sigaddset(&intmask,SIGINT); /* 加入中断 Ctrl+C 信号*/
while(1)
{
/*阻塞信号,不希望保存原来的集合所以参数为 NULL*/
sigprocmask(SIG_BLOCK,&intmask,NULL);
fprintf(stderr,"SIGINT signal blocked\n");
for(i=0;i<repeat_factor;i++)
y=sin((double)i);
fprintf(stderr,"Blocked calculation is finished\n");
/* 取消阻塞 */
sigprocmask(SIG_UNBLOCK,&intmask,NULL);
fprintf(stderr,"SIGINT signal unblocked\n");
for(i=0;i<repeat_factor;i++)
y=sin((double)i);
fprintf(stderr,"Unblocked calculation is finished\n");
}
exit(0);
}


#include <signal.h>;
int sigaction(
4000
int signo,const struct sigaction *act,
struct sigaction *oact);

struct sigaction {
void (*sa_handler)(int signo);
void (*sa_sigaction)(int siginfo_t *info,void *act);
sigset_t sa_mask;
int sa_flags;
void (*sa_restore)(void);
}
/*
signo 要处理的信号,可以是任何的合法的信号.除(SIGKILL 和 SIGSTOP).
act 对这个信号进行如何处理的信息.
oact 以前对这个函数的处理信息,一般为NULL不保存
sa_handler 函数型指针,这个函数有一个参数.这个函数是要进行的信号操作的函数.
sa_sigaction,sa_restore 和 sa_handler 差不多的,只是参数不同,很少使用.
sa_flags 用来设置信号操作的各个情况.一般设置为 0
*/

//使用时用sa_handler指向一个信号操作函数.sa_handler 有两个特殊的值: SIG_DEL 和 SIG_IGN.
//SIG_DEL 是使用缺省的信号操作函数,而 SIG_IGN 是使用忽略该信号的操作函数


实例:

#include <signal.h>;
#include <stdio.h>;
#include <string.h>;
#include <errno.h>;
#include <unistd.h>;
#define PROMPT "你想终止程序吗?"
char *prompt=PROMPT;
void ctrl_c_op(int signo)
{
write(STDERR_FILENO,prompt,strlen(prompt));
}
int main()
{
struct sigaction act;
act.sa_handler=ctrl_c_op;
sigemptyset(&act.sa_mask);
act.sa_flags=0;
if(sigaction(SIGINT,&act,NULL)<0)
{
fprintf(stderr,"Install Signal Action Error: %s\n\a",strerror(errno));
exit(1);
}
while(1);
}
/*如果在信号操作的时候又有一个信号发生,为了处理在信号处理函数运行的时候信号的发生,需要设置 sa_mask 成员. 将要屏蔽的信号添加到 sa_mask 结构当中去,这样这些信号在信号处理的时候就会被屏蔽掉的.*/


3. 其他信号函数

#include <unistd.h>;
#include <signal.h>;
int pause(void);
int sigsuspend(const sigset_t *sigmask);
//pause 函数很简单,就是挂起进程直到一个信号发生了.
//sigsuspend 也是挂起进程只是在调用的时候用 sigmask 取代当前的信号阻塞集合.


#include <sigsetjmp>;
int sigsetjmp(sigjmp_buf env,int val);
void siglongjmp(sigjmp_buf env,int val);
//类似goto 函数或者是 setjmp 和 longjmp 函数.
//这两个信号跳转函数也可以实现程序的跳转, 可以从函数之中跳转到需要的地方.


实例:

这个程序检查用户的邮件.提供了一个开关,如果用户不想程序提示有新的邮件到来,可以向程序发送 SIGUSR2 信号,如果想程序提供提示可以发送 SIGUSR1 信号.

#include <unistd.h>;
#include <stdio.h>;
#include <errno.h>;
#include <fcntl.h>;
#include <signal.h>;
#include <string.h>;
#include <pwd.h>;
#include <sys/types.h>;
#include <sys/stat.h>;
/* Linux 的默任个人的邮箱地址是 /var/spool/mail/ */
#define MAIL_DIR "/var/spool/mail/"
/* 睡眠 10 秒钟 */
#define SLEEP_TIME 10
#define MAX_FILENAME 255
unsigned char notifyflag=1;
long get_file_size(const char *filename)
{
struct stat buf;
if(stat(filename,&buf)==-1)
{
if(errno==ENOENT)
return 0;
else
return -1;
}
return (long)buf.st_size;
}
void send_mail_notify(void)
{
fprintf(stderr,"有新邮件\007\n");
}
void turn_on_notify(int signo)/*邮件提醒开关*/
{
notifyflag=1;
printf("turn_on_notify\r\n");
}
void turn_off_notify(int signo)
{
notifyflag=0;
printf("turn_off_notify\r\n");
}
int check_mail(const char *filename)
{
long old_mail_size,new_mail_size;
sigset_t blockset,emptyset;/*定义两个信号集*/
/*信号集初始化*/
sigemptyset(&blockset);
sigemptyset(&emptyset);
/*设置blockset信号集*/
sigaddset(&blockset,SIGUSR1);
sigaddset(&blockset,SIGUSR2);

old_mail_size=get_file_size(filename);
if(old_mail_size<0)
return 1;
if(old_mail_size>0) /*读取到邮件,发送提醒*/
send_mail_notify();
sleep(SLEEP_TIME);
while(1)
{
if(sigprocmask(SIG_BLOCK,&blockset,NULL)<0) /*屏蔽信号集blockset*/
return 1;

while(notifyflag==0)
sigsuspend(&emptyset);

if(sigprocmask(SIG_SETMASK,&emptyset,NULL)<0) /*信号操作出错*/
return 1;
new_mail_size=get_file_size(filename);
if(new_mail_size>old_mail_size)/*有新邮件*/
send_mail_notify();
old_mail_size=new_mail_size;
sleep(SLEEP_TIME);
}
}
int main(void)
{
char mailfile[MAX_FILENAME];
struct sigaction newact;
struct passwd *pw;
if((pw=getpwuid(getuid()))==NULL)/*获取用户信息出错*/
{
fprintf(stderr,"Get Login Name Error: %s\n\a",strerror(errno));
exit(1);
}
strcpy(mailfile,MAIL_DIR);/*将MAIL_DIR复制到mailfile*/
strcat(mailfile,pw->pw_name);/*将用户名拼接到mailfile*/
printf("mailfile is :%s\r\n",mailfile);

newact.sa_flags=0;
sigemptyset(&newact.sa_mask);

sigaddset(&newact.sa_mask,SIGUSR1);
sigaddset(&newact.sa_mask,SIGUSR2);

/*install sigusr1 interupt handler*/
newact.sa_handler=turn_on_notify;
if(sigaction(SIGUSR1,&newact,NULL)<0)
fprintf(stderr,"Turn On Error: %s\n\a",strerror(errno));
/*install sigusr2 interupt handler*/
newact.sa_handler=turn_off_notify;
if(sigaction(SIGUSR2,&newact,NULL)<0)
fprintf(stderr,"Turn Off Error: %s\n\a",strerror(errno));
check_mail(mailfile);/*check email*/
exit(0);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  linux c语言 编程