kill -9 (SIGKILL)是不可以被进程捕获的,因此是杀死进程的可靠方法
子进程:
- #include <stdlib.h>
-
2 #include <unistd.h>
-
3 #include <sys/types.h>
-
4
-
5 int main(int argc,char* argv[])
-
6 {
-
7 pid_t pid;
-
8
-
9 pid = getpid();
-
10 sleep(20);
-
11
-
12 if(atoi(argv[1]) % 2)
-
13 {
-
14 printf("child process %d kill itself.\n", pid);
-
15 kill(pid, 9);
-
16 }
-
17 else
-
18 {
-
19 printf("child process %d exit.\n", pid);
-
20 _exit(0);
-
21 }
-
22 return 0;
-
23 }
父进程:
- include <stdio.h>
-
2 #include <unistd.h>
-
3 #include <sys/types.h>
-
4 #include <sys/wait.h>
-
5
-
6 int main(int argc, char * argv[])
-
7 {
-
8 pid_t pid,waitpid;
-
9 int status;
-
10 int i;
-
11
-
12 for(i=1;i<argc;i++)
-
13 if(0 == (pid = fork()))
-
14 {
-
15 execlp("./childproc","childproc",argv[i],(char *)NULL);
-
16 }
-
17 else
-
18 {
-
19 printf("child process %d has been created.\n", pid);
-
20 }
-
21
-
22 while((waitpid = wait(&status)) && (-1 != waitpid))
-
23 {
-
24 printf("child process %d exit with code:%d\n",waitpid,status);
-
25 }
-
26 return 0;
-
27 }
其中,当父进程没有子进程可以wait时,wait()返回-1,此时退出while循环。
运行结果:
lisong@lisong:~/code/experiment/proc/wait$ gcc parentproc.c -o parentproc
lisong@lisong:~/code/experiment/proc/wait$ ./parentproc 1 1 2 2 &
[1] 2356
child process 2357 has been created.
lisong@lisong:~/code/experiment/proc/wait$ child process 2358 has been created.
child process 2359 has been created.
child process 2360 has been created.
lisong@lisong:~/code/experiment/proc/wait$ ps
PID TTY TIME CMD
2181 pts/1 00:00:01 bash
2356 pts/1 00:00:00 parentproc
2357 pts/1 00:00:00 childproc
2358 pts/1 00:00:00 childproc
2359 pts/1 00:00:00 childproc
2360 pts/1 00:00:00 childproc
2361 pts/1 00:00:00 ps
lisong@lisong:~/code/experiment/proc/wait$ kill -9 2359
child process 2359 exit with code:9
lisong@lisong:~/code/experiment/proc/wait$ child process 2357 kill itself.
child process 2357 exit with code:9
child process 2358 kill itself.
child process 2358 exit with code:9
child process 2360 exit.
child process 2360 exit with code:0
[1]+ 完成 ./parentproc 1 1 2 2
lisong@lisong:~/code/experiment/proc/wait$ ps
PID TTY TIME CMD
2181 pts/1 00:00:01 bash
2363 pts/1 00:00:00 ps
阅读(1598) | 评论(0) | 转发(0) |