博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
代码示例_进程
阅读量:4310 次
发布时间:2019-06-06

本文共 1648 字,大约阅读时间需要 5 分钟。

进程


 1. fork ,  waitpid

1 #include 
2 #include
3 #include
4 #include
5 6 int main(void) 7 { 8 pid_t pid = fork(); // 创建一个进程 9 10 if(pid<0){11 perror("fork");12 exit(1);13 }14 15 else if(pid==0){16 sleep(3);17 printf("child proc\n");18 }19 20 else if(pid>0){21 sleep(1);22 printf("parent proc\n");23 waitpid(pid,NULL,0); // 阻塞等待回收子进程 不回收成为孤儿进程,24 //waitpid(pid,NULL,WNOHANG); //非阻塞回收子进程25 26 printf("子进程回收成功 !\n");27 28 }29 30 return 0 ;31 }

 

测试:


 

 

 


2. 守护进程:

1 #include 
2 #include
3 #include
4 #include
5 #include
6 #include
7 8 void daemon_init(void) 9 {10 // 1.创建子进程,终止父进程11 pid_t pid = fork();12 if(pid<0){13 perror("fork");14 exit(0);15 }16 else if(pid>0) // 父退出17 exit(0); 18 else if(pid==0){19 20 // 2.在子进程创建会话,setsid()21 setsid();22 23 // 3.忽略SIGHUP信号24 signal(SIGHUP,SIG_IGN);25 26 // 4.再创建进程,终止父进程27 pid=fork();28 if(pid<0){29 perror("fork two");30 exit(1);31 }32 else if(pid>0)33 exit(0);34 35 // 5.关闭文件描述符36 int i,fd_max = sysconf(_SC_OPEN_MAX);37 for(i=0;i<=fd_max;i++)38 close(i);39 40 // 6.将子进程工作目录改为“/”,chdir()41 chdir("/");42 43 // 7.文件权限掩码为0,umask()44 umask(0);45 46 // 8.添加新的文件描述符47 int fd = open("/dev/null",O_RDWR); 48 dup(fd);49 dup(fd);50 }51 }52 53 int main(void)54 {55 56 daemon_init();57 while(1){58 printf("I am daemon \n");59 sleep(2);60 }61 62 return 0;63 }

 

 

 


 

转载于:https://www.cnblogs.com/panda-w/p/11059799.html

你可能感兴趣的文章
referer——防盗链
查看>>
有callback的回调中,不能直接更新UI的解决办法
查看>>
HDU 4123(树上任意点到其他点的最远距离,rmq
查看>>
Redux在React中的使用
查看>>
Linux目录结构
查看>>
玲珑杯#2.5 A-B
查看>>
Educational Codeforces Round 36 (Rated for Div. 2) E. Physical Education Lessons
查看>>
Entity Framewor中的 Migration
查看>>
Redis简介三
查看>>
shell
查看>>
Sed&awk笔记之awk
查看>>
DNS泛解析配置
查看>>
Codeforces Round #351 (VK Cup 2016 Round 3, Div. 2 Edition) D Bear and Two Paths
查看>>
Python学习-day1
查看>>
ORA-06512 问题解决
查看>>
hdu 2049 不容易系列之考新郎 && 对错排的详解
查看>>
10个面向程序员的在线编程网站
查看>>
c#设计模式-单例模式(面试题)
查看>>
WPF x名称空间详解
查看>>
pyenv管理多python版本
查看>>