10 信号处理5

时间:2022-12-19 22:35:11

1. 多次设置进程的处理方式时,进程会使用最新的处理方式:

实例中,alarm使用默认处理方式。

#include "stdio.h"
#include "sys/types.h"
#include "signal.h"
#include "stdio.h"
#include "stdlib.h"
void myfun(int signum)
{
int i;
i=0;
while(i < 10)
{
printf("process signal signum=%d\n",signum);
sleep(1);
i++;
}
return; // return main
}
int main()
{
int i;
i=0;
signal(14,myfun);
printf("alarm before\n");
alarm(9);
printf("alarm after\n");
signal(14,SIG_IGN);
signal(14,SIG_DFL);
while(i< 20)
{
i++;
sleep(1);
printf("process things,i=%d\n",i);
}
return 0;
}
执行结果:
alex@alex-virtual-machine:/extra/process/010$ gcc signal_2.c
alex@alex-virtual-machine:/extra/process/010$ ./a.out
alarm before
alarm after
process things,i=1
process things,i=2
process things,i=3
process things,i=4
process things,i=5
process things,i=6
process things,i=7
process things,i=8
Alarm clock

2. 示例二,进程间信号通信:子进程向父进程发送信号:

a. exit函数传递的信号是SIGCHLD,17

b. 子进程结束时,父进程收到exit信号,通过wait(NULL)函数回收资源。

#include "stdio.h"
#include "sys/types.h"
#include "signal.h"
#include "stdio.h"
#include "stdlib.h"
void myfun(int signum)
{
int i;
i=0;
while(i <5)
{
printf("receive signum=%d,i=%d\n",signum,i);
sleep(1);
i++;
}
return;
}
void myfun1(int signum)
{
printf("receive signum=%d\n",signum);
wait(NULL);
return ;
}

int main()
{
pid_t pid;
pid=fork();
if(pid > 0 )
{
int i;
i=0;
signal(10,myfun);
signal(17,myfun1);
while(1)
{
printf("parent process things,i=%d\n",i);
sleep(1);
i++;
}
}
if(pid == 0)
{
sleep(10);
kill(getppid(),10);
sleep(10);
exit(0);//kill(getppid(),17)
}
return 0;
}
执行结果:

alex@alex-virtual-machine:/extra/process/010$ gcc signal_3.c
alex@alex-virtual-machine:/extra/process/010$ ls
a.out signal_2.c signal_3.c
alex@alex-virtual-machine:/extra/process/010$ ./a.out
parent process things,i=0
parent process things,i=1
parent process things,i=2
parent process things,i=3
parent process things,i=4
parent process things,i=5
parent process things,i=6
parent process things,i=7
parent process things,i=8
parent process things,i=9
receive signum=10,i=0
receive signum=10,i=1
receive signum=10,i=2
receive signum=10,i=3
receive signum=10,i=4
parent process things,i=10
parent process things,i=11
parent process things,i=12
parent process things,i=13
parent process things,i=14
receive signum=17
parent process things,i=15
parent process things,i=16
parent process things,i=17
^C