1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <errno.h>
void restart_real_work(int sig);
void start_real_work();
int main()
{
pid_t pid = fork();
if (pid == -1){
fprintf (stderr,"fork faild %s \n",strerror(errno));
return 0;
}
if (pid == 0){
start_real_work();
}else{
signal( SIGCHLD, restart_real_work);
while (1) {
sleep (6);
}
}
return 0;
}
void start_real_work()
{
/*屏蔽管道破裂信号*/
signal(SIGPIPE, SIG_IGN);
while(1){
printf("working");
sleep(1);
}
}
/*守护信号函数*/
void restart_real_work(int sig)
{
fprintf (stderr,"守护进程\n");
pid_t childPid = waitpid(-1, NULL, 0);
if(childPid <= 0){
return;
}
pid_t pid = fork();
if(pid == -1){
fprintf(stderr, "fork failed, errmsg %s\n", strerror(errno));
return;
}
if(pid == 0){
start_real_work();
}
return ;
}
|