Chinaunix首页 | 论坛 | 博客
  • 博客访问: 149135
  • 博文数量: 26
  • 博客积分: 645
  • 博客等级: 上士
  • 技术积分: 340
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-05 15:00
文章分类

全部博文(26)

文章存档

2014年(1)

2013年(1)

2011年(22)

2010年(1)

2009年(1)

我的朋友

分类: LINUX

2011-06-29 20:42:39

kill -9 (SIGKILL)是不可以被进程捕获的,因此是杀死进程的可靠方法
子进程:
  1. #include <stdlib.h>
  2.   2 #include <unistd.h>
  3.   3 #include <sys/types.h>
  4.   4
  5.   5 int main(int argc,char* argv[])
  6.   6 {
  7.   7 pid_t pid;
  8.   8
  9.   9 pid = getpid();
  10.  10 sleep(20);
  11.  11
  12.  12 if(atoi(argv[1]) % 2)
  13.  13 {
  14.  14 printf("child process %d kill itself.\n", pid);
  15.  15 kill(pid, 9);
  16.  16 }
  17.  17 else
  18.  18 {
  19.  19 printf("child process %d exit.\n", pid);
  20.  20 _exit(0);
  21.  21 }
  22.  22 return 0;
  23.  23 }

父进程:
  1. include <stdio.h>
  2.   2 #include <unistd.h>
  3.   3 #include <sys/types.h>
  4.   4 #include <sys/wait.h>
  5.   5
  6.   6 int main(int argc, char * argv[])
  7.   7 {
  8.   8 pid_t pid,waitpid;
  9.   9 int status;
  10.  10 int i;
  11.  11
  12.  12 for(i=1;i<argc;i++)
  13.  13 if(0 == (pid = fork()))
  14.  14 {
  15.  15 execlp("./childproc","childproc",argv[i],(char *)NULL);
  16.  16 }
  17.  17 else
  18.  18 {
  19.  19 printf("child process %d has been created.\n", pid);
  20.  20 }
  21.  21
  22.  22 while((waitpid = wait(&status)) && (-1 != waitpid))
  23.  23 {
  24.  24 printf("child process %d exit with code:%d\n",waitpid,status);
  25.  25 }
  26.  26 return 0;
  27.  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) |
0

上一篇:execlp

下一篇:waitpid

给主人留下些什么吧!~~