题一:父进程每隔5秒向子进程发送消息,令其打印一句话
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <signal.h>
4 #include <sys/types.h>
5
6 void printMsg(int signo)
7 {
8 printf("father send msg to child/n");
9 };
10
11 main()
12 {
13 pid_t pid = fork();
14 if(pid <0)
15 exit(0);
16 if(pid>0)
17 {
18 while(1)
19 {
20 sleep(5);
21 kill(pid,SIGUSR1);
22 }
23 }
24 else if(pid == 0)
25 {
26 if(signal(SIGUSR1,printMsg)== SIG_ERR)
27 {
28 perror("signal");
29 exit(0);
30 }
31 while(1);
32 }
33 }
题二,按ctrl+c 先父进程打印一句话,后子进程打印一句话
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <signal.h>
4 #include <sys/types.h>
5
6 void printMsgByFather(int signo)
7 {
8 printf("father is over/n");
9 wait();
10 exit(0);
11 };
12 void printMsgBySon(int signo)
13 {
14 sleep(1);
15 printf("son is over/n");
16 exit(0);
17 }
18
19 main()
20 {
21 pid_t pid = fork();
22 if(pid <0)
23 exit(0);
24 if(pid>0)
25 {
26 if(signal(SIGINT,printMsgByFather)== SIG_ERR)
27 {
28 perror("signal");
29 exit(0);
30 }
31 while(1);
32 }
33 else if(pid == 0)
34 {
35 if(signal(SIGINT,printMsgBySon)== SIG_ERR)
36 {
37 perror("signal");
38 exit(0);
39 }
40 while(1);
41 }
42 }