信号捕捉函数(sigaction),项目实战强烈推荐
结构介绍
struct sigaction {
void (sa_handler)(int); / 信号的响应函数 /
sigset_t sa_mask; / 屏蔽信号集 /
int sa_flags; / 当sa_flags中包含 SA_RESETHAND时,接受到该信号并调用指定的信号处理函数执行之后,把该信号的响应行为重置为默认行为SIG_DFL */
…
}
输入字符a的大小写,发送信号,使输出语句变为大小写。
#include <stdio.h>
#include <stdlib.h>
#include<unistd.h>
#include <signal.h>
int workflag = 0;
void work_up_handle(int sig)
{
workflag = 1;
}
void work_down_handle(int sig)
{
workflag = 0;
}
int main(void)
{
pid_t pd;
char c;
pd = fork();
if (pd == -1) {
printf("fork error!\n");
exit(1);
} else if (pd == 0) {
char *msg;
struct sigaction act;
act.sa_flags = 0;
act.sa_handler = work_up_handle;
sigemptyset(&act.sa_mask);
sigaction(SIGUSR1, &act, 0);
act.sa_handler = work_down_handle;
sigaction(SIGUSR2, &act, 0);
while (1) {
if (!workflag) {
msg = "child process work!";
} else {
msg = "CHILD PROCESS WORK!";
}
printf("%s\n", msg);
sleep(1);
}
} else {
while(1) {
c = getchar();
if (c == 'A') {
kill(pd, SIGUSR1);
} else if (c == 'a') {
kill(pd, SIGUSR2);
}
}
}
return 0;
}
*实例:main7.c “闹钟”,创建一个子进程,子进程在5秒钟之后给父进程发送一个SIGALRM,父进程收到SIGALRM信号之后,“闹铃”(用打印模拟)
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
int wakeflag = 0;
void wake_handle(int sig)
{
wakeflag = 1;
}
int main(void)
{
pid_t pd;
char c;
pd = fork();
if (pd == -1) {
printf("fork error!\n");
exit(1);
} else if (pd == 0) {
sleep(5);
kill(getppid(), SIGALRM);
} else {
struct sigaction act;
act.sa_handler = wake_handle;
act.sa_flags = 0;
sigemptyset(&act.sa_mask);
sigaction(SIGALRM, &act, 0);
pause(); //把该进程挂起,直到收到任意一个信号
if (wakeflag) {
printf("Alarm clock work!!!\n");
}
}
return 0;
}