c++创建一个linux deamon进程
2018-02-09 17:11
429 查看
正规的方法, 创建一个deamon进程,需要很多步骤
1. fork()
2. 子进程setsid()
3. 主进程wait()
4. chdir()
5. umask()
非正规方法创建一个deamon进程的步骤:
1. 创建一个子进程fork(), 创建子进程的目的是为了后面的设置进程组ID.
2. 子进程执行setsid(), 执行setsid()有两个目的, 一是创建一个新的会话,二是设置进程组ID.
3. 主进程wait()
每个函数都有他的意义.稍后再研究一下:
创建一个deamon进程
输出:
子进程退出后, 主进程仍然能正确启动子进程的demo:
输出:
僵尸进程:
僵尸进程, 是指子进程先于父进程退出, 且退出时, 父进程没有收到子进程的退出信号.
输出:
1. fork()
2. 子进程setsid()
3. 主进程wait()
4. chdir()
5. umask()
非正规方法创建一个deamon进程的步骤:
1. 创建一个子进程fork(), 创建子进程的目的是为了后面的设置进程组ID.
2. 子进程执行setsid(), 执行setsid()有两个目的, 一是创建一个新的会话,二是设置进程组ID.
3. 主进程wait()
每个函数都有他的意义.稍后再研究一下:
创建一个deamon进程
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> int main(int argc, char *argv[]) { int n = fork(); pid_t pid; fprintf(stdout, "PID:%d, PGID:%d, SID:%d\n", getpid(), getpgrp(), getsid(0)); int stat = 0; if (n > 0) { pid_t x = wait(&stat); printf("child pid=%d\n", x); if(WIFEXITED(stat) == 0) { printf("child normal exited!\n"); } } else if (n == 0) { if(setsid() < 0) { fprintf(stderr, "setsid error:%s\n", strerror(errno)); } while(1) { printf("child.\n"); sleep(1); } } return 0; }
输出:
子进程退出后, 主进程仍然能正确启动子进程的demo:
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> int main(int argc, char *argv[]) { while(1) { int n = fork(); pid_t pid; fprintf(stdout, "PID:%d, PGID:%d, SID:%d\n", getpid(), getpgrp(), getsid(0)); int stat = 0; if (n > 0) { pid_t x = wait(&stat); printf("child pid=%d\n", x); if(WIFEXITED(stat) == 0) { printf("child normal exited!\n"); } } else if (n == 0) { if(setsid() < 0) { fprintf(stderr, "setsid error:%s\n", strerror(errno)); } while(1) { printf("child.\n"); sleep(1); } } sleep(5); } return 0; }
输出:
僵尸进程:
僵尸进程, 是指子进程先于父进程退出, 且退出时, 父进程没有收到子进程的退出信号.
#include <unistd.h> #include <stdio.h> int main(int argc, char *argv[]) { int n = fork(); pid_t pid; fprintf(stdout, "PID:%d, PGID:%d, SID:%d\n", getpid(), getpgrp(), getsid(0)); if (n > 0) { while(1) { printf("parent.\n"); sleep(1); } } else if (n == 0) { printf("child.\n"); } return 0; }
输出:
相关文章推荐
- 第六周分析Linux内核创建一个新进程的过程
- Linux内核作业--分析Linux内核创建一个新进程的过程
- 创建守护进程步骤与setsid() -- linux deamon进程
- Linux内核分析6:分析Linux内核创建一个新进程的过程
- 实验 六:分析linux内核创建一个新进程的过程
- Linux编写一个孤儿进程,这个孤儿进程可以同时创建100个僵死进程。
- 分析Linux内核创建一个新进程的过程
- Linux如何创建一个进程
- 分析Linux内核创建一个新进程的过程
- [网易云课堂]Linux内核分析(六)—— 分析Linux内核创建一个新进程的过程
- Linux如何创建一个新进程
- lab6:分析Linux内核创建一个新进程的过程
- 分析Linux内核创建一个新进程的过程
- linux 一个简单的进程创建例子
- 分析Linux内核创建一个新进程的过程
- 《Linux 内核分析》第六周:分析Linux内核创建一个新进程的过程
- windows c++程序员开始用linux编程(二)创建新进程
- 分析Linux内核创建一个新进程的过程
- [转载] 分析Linux内核创建一个新进程的过程
- Unix/Linux如何创建一个后台进程(run background process)