unix 高级编程学习 --进程

来源:互联网 发布:光伏数据采集器接法 编辑:程序博客网 时间:2024/06/05 22:46

进程

进程创建

函数

#include <unistd.h>
fork()函数

记住条件

1.创建返回0,则是当前子进程。
2.创建返回大于0,则是父进程。
3.如果创建出错则是-1.

简单代码例子

#include<stdio.h>#include<stdlib.h>#include<unistd.h>int main(void){pid_t pid = 0;pid = fork();if(pid<0){printf("fork is error\n");exit(0);}else if(pid > 0){//父亲进程printf("perent = %d\n",getppid());sleep(2);}else if(pid == 0){printf("子进程 = %d\n",getpid());}return 0;}

进程之间共享

#include <stdio.h>#include <stdlib.h>#include <unistd.h>int global = 1;//全局变量int main(void){pid_t pid;int stack = 1;int *head = NULL;head = (int *)malloc(sizeof(int));if(head < 0){printf("malloc is error\n");exit(0);}*head = 3;pid = fork();if(pid < 0){printf("fork() is error\n");exit(-1);}if(pid == 0){stack ++;(*head)++;global ++;printf("子进程%d%d%d\n",stack,(*head),global);}else{//sleep(2);printf("父进程%d%d%d\n",stack,(*head),global);}return 0;}

进程消除

函数

#include <stdlib.h>
exit();
_exit();

区别

exit 还有会有缓存。

_exit直接删除所有缓存数据。

代码

#include <stdio.h>#include <stdlib.h>int main(void){printf("user exit\n");printf("还有缓存\n");exit(0);}

#include <stdio.h>#include <stdlib.h>#include <unistd.h>int main(void){printf("111111111\n");printf("2222222222222");_exit(0);}

僵尸进程与孤儿进程

孤儿进程

孤儿进程:很形象的比喻,就是父进程退出没有对子进程进行监听所产生的。
僵尸进程:就是子进程退出,父进程没有监听子进程退出产生的。

代码

出现僵尸程序。
#include <unistd.h>#include <stdio.h>#include <stdlib.h>int main(void){pid_t pid;pid = fork();if(pid<0){printf("fork is error\n");exit(0);}else if(pid == 0){printf("child is run\n");exit(0);}else {sleep(4);printf("perent is run\n");}return 0;}

输入命令ps aux | grep -w 'Z'查看僵尸进程。

解决方案:

1.wait解决
#include <unistd.h>#include <stdlib.h>#include <stdio.h>#include <sys/wait.h>#include <sys/types.h>int main(void){pid_t pid;pid = fork();if(pid <0){exit(0);}else if(pid > 0){pid_t p = wait(NULL);printf("父进程运行p = %d\n",p);}else{printf("子进程在运行\n");exit(0);}return 0;}

2.waitipd
#include <sys/types.h>#include <sys/wait.h>#include <unistd.h>#include <stdio.h>#include <stdlib.h>int main(void){pid_t pid,pre;pid = fork();if(pid<0){exit(0);}else if(pid == 0){printf("id = %d",getpid());sleep(10);exit(0);}else{do{pre = waitpid(pid,NULL,WNOHANG);if(pre == 0){printf("没有进程退出\n");sleep(1);}}while(pre == 0);if(pre == pid){printf("找到退出的子进程%d\n",pre);}else{printf("出现出错\n");}}return 0;}