(转载)Linux使用prctl API, 在父进程退出后,让子进程也退出
2013-05-07 15:56
393 查看
例子1:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <sys/prctl.h> void my_system(void) { pid_t pid; pid = fork(); if (pid == 0) { //prctl(PR_SET_PDEATHSIG, SIGHUP); while (1) { printf("child running...\n"); sleep(1); } exit(0); } else if (pid < 0) { printf("create failed\n"); } } int main (int argc, char *argv[]) { int i = 0; my_system(); while (i++ < 6) { printf("father running...\n"); sleep(1); } printf("Main exit()\n"); return 0; }
程序输出:
[root@localhost ~]# ./a.out
child running...
father running...
child running...
father running...
child running...
father running...
child running...
father running...
child running...
father running...
child running...
father running...
child running...
Main exit()
[root@localhost ~]# child running...
child running...
child running...
child running...
child running...
child running...
可以看到当父进程结束了,子进程还在运行,此时的子进程变成了孤儿进程了。
例子2:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <sys/prctl.h> void my_system(void) { pid_t pid; pid = fork(); if (pid == 0) { // 设置当父进程退出时,子进程也退出 prctl(PR_SET_PDEATHSIG, SIGHUP); while (1) { printf("child running...\n"); sleep(1); } exit(0); } else if (pid < 0) { printf("create failed\n"); } } int main (int argc, char *argv[]) { int i = 0; my_system(); while (i++ < 6) { printf("father running...\n"); sleep(1); } printf("Main exit()\n"); return 0; }
程序输出:
[root@localhost ~]# ./a.out
child running...
father running...
child running...
father running...
child running...
father running...
child running...
father running...
father running...
child running...
father running...
child running...
child running...
Main exit()
[root@localhost ~]#
[root@localhost ~]#
[root@localhost ~]#
从程序输出可以看到当父进程退出了,那么子进程也就退出了。
相关文章推荐
- 使用prctl API, 在父进程退出后,让子进程也退出
- linux 让父进程等待并检查子进程的退出状态
- linux系统编程之进程(四):进程退出exit,_exit区别即atexit函数(转载)
- [Linux进程]使用waitpid函数退出进程
- linux使用共享内存通信的进程同步退出问题
- [Linux进程]在父进程和子进程中分别使用execl函数
- Unix/Linux中进程控制相关命令总结&, jobs, fg, bg等命令的使用方法
- linux socket tcp server 解决客户端socket断开后, 服务器端进程退出的问题
- Linux上获取指定进程的cpu使用情况
- 使用C#制做进程监视器 (转载)
- linux下对进程出错退出的重启
- 在Linux系统中使用xkill命令杀掉未响应的进程
- LINUX 使用top 查看动态进程
- 使用 shell 脚本对 Linux 系统和进程资源进行监控
- linux 用vi命令的使用以及vi编辑后的后续保存退出等相关命令的使用
- Linux进程退出详解(do_exit)--Linux进程的管理与调度(十四))
- 关于linux下内存使用的一些疑惑[转载]
- linux下查看进程内存使用情况
- linux进程优先级、进程nice值(转载)
- J2ME中使用pauseApp控制手机临时退出JAVA程序(转载)