- 前言
- 一、进程管理
- 二、进程同步
- 总结
前言
这次是进程管理的最后一部分内容,主要复习进程管理除fork()外的其他函数,还有一部分进程同步。
一、进程管理1、函数
exec族
exit()
2、案例 1.exec族exec函数族中包含6个函数,分别为:
#include2.案例代码int execl(const char *path, const char *arg, ...); int execlp(const char *file, const char *arg, ...); int execle(const char *path, const char *arg, ..., char * const envp[]); int execv(const char *path, char * const argv[]); int execvp(const char *file, char * const argv[]); int execve(const char *path, char * const argv[], char * const envp[]);
#include运行结果: exit函数#include #include int main(){ pid_t tempPid; tempPid=fork(); if(tempPid==-1){ perror("fork error"); exit(-1); }else if(tempPid>0){ printf("parent process : pid=%dn",getpid()); }else{ printf("child process : pid=%dn",getpid()); char *arg[]={"-a","-l","main.c",NULL}; execvp("ls",arg); perror("error execn"); printf("child process : pid=%dn",getpid()); }//of if return 0; }//of main
格式:
void exit(int status);
参数status即状态,为0时正常退出,其它值为异常退出,但其实exit是一个集成的函数,也就是被封装过的,在exit封装内部有一个核心函数,_exit(),当遇到一个函数是以下划线开头,那么这个函数会更贴近于底层。安全性:exit > _exit,区别:exit需要进行判断做一些处理,_exit无条件退出。
孤儿进程与僵尸进程区别孤儿进程:父进程负责回收子进程,如果父进程先于子进程退出,子进程就会变成孤儿进程,此时由init进程完成对子进程的回收工作;
僵尸进程:调用exit函数后,该进程不会马上消失,而是变成僵尸进程。它几乎放弃进程退出前占用的所有内存,但是会占据进程号,没有可执行代码也不能被调度,记载进程的退出状态等信息供父进程回收。若父进程没有回收子进程的代码,子进程将会一直处于僵尸态,不会被init回收。一直累积,会由于没有进程号分配,导致系统崩溃。
二、进程同步 1、wait函数pid_t wait(int *status);
功能:挂起进程,进程进入阻塞状态,直到子进程变为僵尸态,如果捕获到子进程的退出信息就会转为运行态,然后回收子进程资源并返回;若没有变为僵尸态的子进程,wait函数就会让进程一直阻塞。若当前进程有多个子进程,只要捕获到一个变为僵尸态的子进程,wait函数就会恢复执行态。
参数:参数status是一个int *类型的指针,用来保存子进程退出时的状态信息。通常情况下该参数设为NULL,表示不关心进程时如何终止的。
状态:
成功:返回子进程的进程id;
失败:返回-1,errno被设置为ECHILD
案例1:若子进程 p1是其父进程 p的先决进程,基于wait函数使得进程同步。
#include#include #include int main(){ pid_t tempPid,tempW; tempPid=fork(); if(tempPid==-1){ perror("fork error"); exit(1); }else if(tempPid==0){//child sleep(3); printf("child process:pid=%d,ppid=%dn",getpid(),getppid()); }else{ tempW=wait(NULL); printf("Catched a child process, pid = %d, ppid=%dn",tempW,getppid()); }//of if printf("--------finish--------n"); return 0; }// of main
案例二:使用wait同步进程,并使用宏获取子进程的返回值。
#include#include #include int main(){ int tempStatus; pid_t tempPid,tempW; tempPid=fork(); if (tempPid==-1){ perror("fork error"); exit(1); }else if(tempPid==0){//child sleep(3); printf("Child process : pid = %dn",getpid()); exit(5); }else{ tempW=wait(&tempStatus); if(WIFEXITED(tempStatus)){ printf("Child process pid = %d exit normally.n",tempW); printf("Return Code:%dn",WEXITSTATUS(tempStatus)); }else{ printf("child process pid = %d exit abnormally.n",tempW); }//of if }//of if return 0; }//of main
总结
这里是对文章的初步总结,后续还有一个waitpid()函数需要复习。



