• 【Linux系统编程】进程控制



    在这里插入图片描述

    1.进程创建

    进程创建OS会做什么?
    • 创建大量内核数据结构对象、变量
    • 针对各种数据结构初始化
    • 加载部分或者全部程序对应的代码和数据
    • 建立映射关系
    • 将进程连入各种数据结构中,task_struct—>runqueue,blockqueue

    fork()函数

    #include
    pid_t fork(void);
    返回值:自进程中返回0,父进程返回子进程id,出错返回-1
    
    • 1
    • 2
    • 3

    进程调用fork,当控制转移到内核中的fork代码后,内核做:

    • 创建大量的内核数据结构对象,分配新的内存块【task_struct】和内核数据【mm_struct】结构给子进程
    • 将父进程部分数据结构内容拷贝至子进程
    • 添加子进程到系统进程列表当中
    • fork返回,开始调度器调度

    image-20220814143656173

    为什么子进程从fork()之后开始执行?

    image-20220814150204080

    ​ eip叫做程序计时器【也叫pc指针/指令指针】,保存当前正在执行指令的下一条指令。创建子进程的时候,会把eip也拷贝给子进程,子进程就从eip中的指令【也就是fork()的下一条执行】开始执行。

    1.1写时拷贝

    ​ fork()之后,父子共享所有的代码。通常,父子代码共享,父子再不写入时,数据也是共享的,当任意一方试图写入,便以写时拷贝的方式各自一份副本。

    image-20220814150259896

    为什么有写时拷贝?

    • 父进程的数据,子进程不一定全用。会有浪费空间的问题。
    • 最理想的情况,只有会被父子修改的数据,进行分离拷贝,这种操作难以实现。
    • 如果创建子进程,直接将子进程拷贝给子进程,会增加fork()的成本。
    • 写时拷贝是一种延缓拷贝的策略。
    1.2 fork常规用法

    ​ 一个父进程希望复制自己,使父子进程同时执行不同的代码段。例如,父进程等待客户端请求,生成子进程来处理请求。
    ​ 一个进程要执行一个不同的程序。例如子进程从fork返回后,调用exec函数。
    fork调用失败的原因
    ​ 系统中有太多的进程
    ​ 实际用户的进程数超过了限制

    1.3进程终止

    ​ C/C++程序,main函数也叫做入口函数,在虚拟地址空间中main函数的地址往往是确定的。

    常见的进程退出

    • 代码运行完毕,结果正确
    • 代码运行完毕,结果不正确
    • 代码异常终止

    关于return的返回值

    • 进程代码跑完,结果正确应该返回0,失败返回非零。
    • 如果想知道失败的原因,可以用非零标识不同的原因。return X,也叫进程退出码。
    • 进程退出码最后返回给了父进程。
    echo $?     
    该命令的作用:返回bash中,最后一次接收的进程退出码
    
    • 1
    • 2

    image-20220814155307473

    进程常见退出方法
    正常终止(可以通过 echo $? 查看进程退出码):

    • 从main函数中return。其他函数return表示函数调用结束。
    • 在自己的代码中的任意位置调用exit()
    • _exit

    异常退出:

    • ctrl + c,信号终止
    #include 
    void exit(int status);
    参数:status 定义了进程的终止状态,父进程通过wait来获取该值
    #include 
    void _exit(int status);
    参数:status 定义了进程的终止状态,父进程通过wait来获取该值
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    _exit和exit函数的关系

    exit最后也会调用_exit, 但在调用exit之前,还做了其他工作:

    • 执行用户通过 atexit或on_exit定义的清理函数。
    • 关闭所有打开的流,所有的缓存数据均被写入
    • exit终止进程,刷新缓冲区;_exit终止进程,但是不刷新缓冲区。
    • 调用_exit

    image-20220814163322454

    使用exit,进程退出刷新缓冲区

     int main()
     {
         printf("hello world");
         exit(0);
         return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    image-20220814164551829

    使用_exit,进程退出不会刷新缓冲区

     int main()
     {
         printf("hello world");
         _exit(0);
         return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    image-20220814164711854

    2.进程等待

    • 子进程退出,父进程如果不管不顾,就可能造成‘僵尸进程’的问题,进而造成内存泄漏。
    • 另外,进程一旦变成僵尸状态,kill -9 也无法杀死僵尸进程,因为谁也没有办法杀死一个已经死去的进程。
    • 最后,父进程派给子进程的任务完成的如何,我们需要知道。如,子进程运行完成,结果对还是不对,或者是否正常退出。
    • 父进程通过进程等待的方式,回收子进程资源,获取子进程退出信息
    2.1进程等待的方法
    2.1.1wait方法
    #include
    #include
    pid_t wait(int*status);
    返回值:
    	成功返回被等待进程pid,失败返回-1。
    参数:
    	输出型参数,获取子进程退出状态,不关心则可以设置成为NUL
    说明:
        wait函数会阻塞等待
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    2.1.2waitpid
    pid_ t waitpid(pid_t pid, int *status, int options);
    返回值:
    	当正常返回的时候waitpid返回收集到的子进程的进程ID;
    	如果设置了选项WNOHANG,而调用中waitpid发现没有已退出的子进程可收集,则返回0;
    	如果调用中出错,则返回-1,这时errno会被设置成相应的值以指示错误所在;
    参数:
    pid:
    	Pid=-1,等待任一个子进程。与wait等效。
    	Pid>0.等待其进程ID与pid相等的子进程。
         pid< -1   如果一个进程组ID为pid,传入-pid可以回收该进程组
         pid=0     回收和调用进程组ID相同的组内子进程
        
    status:【输出型参数】
    	WIFEXITED(status): 若为正常终止子进程返回的状态,则为真。(查看进程是否是正常退出)
    	WEXITSTATUS(status): 若WIFEXITED非零,提取子进程退出码。(查看进程的退出码)
            
    options:
    	WNOHANG: 若pid指定的子进程没有结束,则waitpid()函数返回0,不予以等待。若正常结束,则返回该子进程的ID。
         WUNTRACED:暂停状态
         0和wait相同,会发生阻塞等待
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    2.2获取status

    ​ **进程在退出时,会将自己的退出信息写入task_struct模块中。**父进程就可以通过status获取进程退出信息。

    • wait和waitpid,都有一个status参数,该参数是一个输出型参数,由操作系统填充。
    • 如果传递NULL,表示不关心子进程的退出状态信息。
    • 否则,操作系统会根据该参数,将子进程的退出信息反馈给父进程。
    • status不能简单的当作整形来看待,可以当作位图来看待,具体细节如下图(只研究status低16比特位):

    image-20220814174325445

    第8为到15为存放的是进程退出码,因此我们可以想办法获取status的次低8位获取退出码

    #include
    #include
    #include
    #include
    #include
    int main()
    {
        pid_t pid=fork();
        if(pid==0)
        {
            int cnt=5;
            while(1)
            {
                printf("我是子进程,我正在运行......pid=%d\n",getpid());
                sleep(1);
                cnt--;
                if(!cnt)
                {
                    break;
                }
            }
            exit(13);
        }
        else
        {
            int status=0;
            printf("我是父进程,pid=%d,我准备等待子进程:%d\n",getpid());
            pid_t ret=waitpid(pid,&status,0);
            if(ret>0)
            {
                printf("wait sucess,ret:%d,我等待的推出码是:%d\n",ret,(status>>8)&0xFF);
            }
            sleep(10);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    在这里插入图片描述

    status的最低7位存放:进程异常退出时得到的信号

    #include
    #include
    #include
    #include
    #include
    
    int main()
    {
        pid_t pid=fork();
        if(pid==0)
        {
            while(1)
            {
                printf("我是子进程,我正在运行......pid=%d\n",getpid());
                sleep(1);
            }
            exit(13);
        }
        else
        {
            int status=0;
            printf("我是父进程:pid=%d,我准备wait子进程\n",getpid());
            pid_t ret=waitpid(pid,&status,0);
            printf("我等待的子进程是:ret=%d,退出码:%d,异常码:%d\n",ret,(status>>8)&0xFF,status&0x7F);
            sleep(10);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    在这里插入图片描述

    获取退出码

    int main()
    {
        pid_t pid=fork();
        if(pid==0)
        {
            int cnt=5;
            while(1)
            {
                printf("我是子进程,我正在运行......pid=%d\n",getpid());
                sleep(1);
                cnt--;
                if(!cnt)
                {
                    break;
                }
            }
            exit(13);
        }
        else
        {
            int status=0;
            printf("我是父进程,pid=%d,我准备等待子进程:%d\n",getpid());
            pid_t ret=waitpid(pid,&status,0);
    		if(WIFEXITED(status))
            {
                printf("我等待的子进程是:ret=%d,退出吗是:%d\n",ret,WEXITSTATUS(status));
            }
            sleep(10);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    在这里插入图片描述

    2.3非阻塞等待
    int main()
    {
    	pid_t pid;
    	pid = fork();
    	if(pid < 0)
        {
    		printf("%s fork error\n",__FUNCTION__);
    		return 1;
    	}
        else if( pid == 0 ){ //child
    		printf("child is run, pid is : %d\n",getpid());
    		sleep(5);
    		exit(1);
    	}
        else{
    		int status = 0;
    		pid_t ret = 0;
    		do
    		{
    			ret = waitpid(-1, &status, WNOHANG);//非阻塞式等待
    			if( ret == 0 ){
    				printf("child is running\n");
    			}
    			sleep(1);
    		}while(ret == 0);
    	if( WIFEXITED(status) && ret == pid ){
    		printf("wait child 5s success, child return code is:%d.\n",WEXITSTATUS(status));
    	}
        else{
    		printf("wait child failed, return.\n");
    		return 1;
    		}
    	}
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    shell脚本

    while :; do ps ajx | head -1 && ps ajx |grep process |grep -v grep; sleep 1; echo "##################################"; done
    
    • 1

    3.进程程序替换

    • 子进程在创建的时候会共享父进程的数据和代码,如果不对子进程的代码做修改,那么子进程就会完成和父进程相同的程序。
    • 而想要子进程完成和父进程不一样的动作,一种方式就是程序替换。

    子进程往往要调用一种exec函数以执行另一个程序。当进程调用一种exec函数时,该进程的用户空间代码和数据完全被新程序替换,从新程序的启动例程开始执行。调用exec并不创建新进程,所以调用exec前后该进程的id并未改变。

    3.1进程程序替换原理

    在程序替换前,父进程的页表左端和子进程的页表左端都是映射同一个可执行程序a.exe的物理地址

    image-20220930114455279

    当子进程被替换为可执行程序b.exe时,子进程页表的左端映射发生变化,映射为b.exe的物理地址

    在这里插入图片描述

    程序替换的原理

    • 将磁盘中的程序加载到内存结构中
    • 重新建立页表映射,谁执行程序替换,就重新建立谁的映射

    效果:父进程和子进程彻底分离,并入子进程执行一个全新的程序

    #include
    #include
    #include
    #include
    int main()
    {
        pid_t id=fork();
        if(id==0)
        {
            printf("我是子进程,pid=%d",getpid());
            execl("/usr/bin/ls","ls","-l","-a",NULL);
            printf("我是子进程,程序替换结束\n");
            exit(1);
        }
        int status=0;
        int ret=waitpid(id,&status,0);
        if(ret==id)
        {
            sleep(2);
            printf("父进程等待成功\n");
        }
        printf("我是父进程,pid=%d\n",getpid());
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    在这里插入图片描述

    打印结果表明程序替换确实成功,但是是不是少打印了一句?

    程序一旦替换成功,当前进程的代码和数据全部被替换,页表映射到新的程序中,所以后续程序都不会运行。

    程序替换需要判断返回值吗?

    • 不用判断返回值:只要替换成功,就不会有返回值
    • 替换失败,进程后面的代码会正常的执行
    • 返回值的作用是得到什么原因导致的替换失败

    替换bash脚本

    bash脚本

    #!usr/bin/bash
    
    cnt=0;
    while [ $cnt -le 100]
    do 
    	echo "hello $cnt"
    	let cnt++
    done
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    主程序

    #include
    #include
    #include
    #include
    int main()
    {
        pid_t id=fork();
        if(id==0)
        {
            printf("我是子进程,pid=%d",getpid());
            execl("/usr/bin/bash","bash","test.sh",NULL);
            printf("我是子进程,程序替换结束\n");
            exit(1);
        }
        int status=0;
        int ret=waitpid(id,&status,0);
        if(ret==id)
        {
            sleep(2);
            printf("父进程等待成功\n");
        }
        printf("我是父进程,pid=%d\n",getpid());
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    在这里插入图片描述

    3.2进程替换函数

    常见的进程替换函数

    #include 
    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[]);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • l(list) : 表示参数采用列表
    • v(vector) : 参数用数组
    • p(path) : 有p自动搜索环境变量PATH
    • e(env) : 表示自己维护环境变量

    函数用法示例

    char *const argv_[]={
        (char*)"ls",
        (char*)"-a",
        (char*)"-l",
        (char*)"-l",
        NULL
    };
    execvp("ls",argv_);
    execlp("ls","ls","-l","-a",NULL);
    execv("/usr/bin/ls",argv_);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    需要自己维护环境变量的exec函数

    int execle(const char *path, const char *arg, ...,char *const envp[]);
    int execve(const char *path, char *const argv[], char *const envp[]);
    
    • 1
    • 2

    以接口execle为例

    mycmd.cpp

    #include
    #include
    int main()
    {
       std::cout<<"PATH:"<<getenv("PATH")<<std::endl;
       std::cout<<"#################################"<<std::endl;
       std::cout<<"MySetPATH"<<getenv("MySetPATH")<<std::endl;  
       std::cout<<"#################################"<<std::endl;
       for(int i=0;i<8;i++)
       {
         std::cout<<"hello C++"<<std::endl;
       }
       return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    exec.c

    #include
    #include 
    #include
    #include
    #include
    int main()
    {
       pid_t id=fork();
       if(id==0)
       {
         printf("我是子进程,pid=%d\n",getpid());
         //设置环境变量
         char* const env_[]={
         (char*)"MySetPATH=This is my PATH",
         NULL
         };
           
         //进程程序替换为mycmd
         execle("./mycmd","mycmd",NULL,env_);
         printf("我是子进程,程序替换接收\n");
         exit(1);
       }
       //程序替换后,执行到这里的只能是父进程
       int status=0;
       int ret=waitpid(id,&status,0);
       if(ret==id)
       {
         sleep(2);
         printf("父进程等待成功\n");
       }
       printf("我是父进程,pid=%d\n",getpid());
       return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    在这里插入图片描述

    可以看到,mycmd在运行到打印PATH时就崩溃退出了,假如我们把

     std::cout<<"PATH:"<<getenv("PATH")<<std::endl;
    
    • 1

    代码注释掉。

    在这里插入图片描述

    可以看到,程序可以正常的运行。

    原因:我们在设置环境变量env_的时候,是覆盖式的设置,将原来复制父进程的环境变量覆盖掉,所以子进程中不存在PATH环境变量,导致程序最后崩溃了。

    修改方法:

    可以先添加环境变量

    export MySetPATH="This is my PATH"
    #查看环境变量是否添加成功
    env|grep -i MySetPATH
    
    输出:MySetPATH=This is my PATH
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在exec.c中获取环境变量

    extern char** environ;
    execle("./mycmd","mycmd",NULL,envrion);
    
    • 1
    • 2

    在这里插入图片描述

    4.自定义简易shell脚本

    #include
    #include
    #include
    #include
    #include
    #include
    #define SEP " "
    
    char sin[1024];
    char* sin_arg[128];
    int main()
    {
       while(1)
       {
         printf("[west@shadow myshell]$ \n");
         memset(sin,'\0',sizeof(sin));
         //阻塞等待用户输入                                               
         //读取用户输入,由于用户输入存在空格,所以不能使用scanf函数
         //fgets遇到换行读取结束                          
         fgets(sin,1024,stdin);    
         sin[strlen(sin)-1]='\0'; 	//清空\n
         //将得到的参数,按照空格为分割,可以使用strtok函数
         sin_arg[0]=strtok(sin,SEP);
         int i=0;                               
         //截取失败,返回NULL                   
         while(sin_arg[++i]=strtok(NULL,SEP)){;}
       }
       return 0;               
    } 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    运行试试效果

    在这里插入图片描述

    可以看到,每次打印完前面的[west@shadow myshell]$,光标的位置都是处于下一行的开头。原因是:\n代表回车换行,现在我们想要光标留在本行的后面,只需要去掉\n再使用fflush刷新缓冲区即可

         printf("[west@shadow myshell]$ ");
    	fflush(stdout);
         memset(sin,'\0',sizeof(sin));
         //阻塞等待用户输入                                               
         //读取用户输入,由于用户输入存在空格,所以不能使用scanf函数
         //fgets遇到换行读取结束                          
         fgets(sin,1024,stdin);  
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    再执行一次

    在这里插入图片描述

    现在只需要加上程序替换函数就可以实现简单的shell

    #include
    #include
    #include
    #include
    #include
    #include 
    #define SEP " "
    char sin[1024];
    char* sin_arg[128]; 
    int main()
    {
        while(1)
       {
         printf("[west@shadow myshell]$ ");
         fflush(stdout);
         memset(sin,'\0',sizeof(sin));
         //阻塞等待用户输入
         //读取用户输入,由于用户输入存在空格,所以不能使用scanf函数
         //fgets遇到换行读取结束
         fgets(sin,1024,stdin);
         sin[strlen(sin)-1]='\0';
         //将得到的参数,按照空格为分割,可以使用strtok函数              
         sin_arg[0]=strtok(sin,SEP);
         int i=0;
         //截取失败,返回NULL
         while(sin_arg[++i]=strtok(NULL,SEP)){;}
         pid_t pid=fork();
         if(pid==0)
         {
           //这里sin_arg[0]保存的就是想要执行的指令名称
           execvp(sin_arg[0],sin_arg);
           exit(1);
         }
         int status=0;
         pid_t ret=waitpid(pid,&status,0);
         if(ret<0)
         {
    		printf("进程等待失败,sig=%d,code=%d\n",status&0x7f,(status>>8)&0xff);
         }
       }
       return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

    在这里插入图片描述

  • 相关阅读:
    【错误记录】IntelliJ IDEA 导出可执行 jar 包执行报错 ( java.lang.ClassNotFoundException | 打包时没有选择依赖库 )
    毅速丨为什么不锈钢材料在金属3D打印中应用广泛
    夜天之书 #60 面向人力资源的 GitHub 指南
    Linux信号
    春秋云镜 CVE-2014-4577
    halcon 圆点标定板相关算法说明及使用方法
    Android 自定义加解密播放音视频(m3u8独立加密)
    箱形理论在交易策略中的实战应用与优化
    D. Divide(math)[2021 ECNU Campus Invitational Contest]
    常见的网络设备
  • 原文地址:https://blog.csdn.net/qq_53893431/article/details/127131137