Linux进程控制

目录

进程创建

fork函数初识

fork函数返回值

写时拷贝

fork常规用法

fork调用失败的原因

进程终止

进程退出场景

进程常见退出方法

_exit函数

exit函数

return退出

进程等待

进程等待必要性

进程等待的方法

wait方法

waitpid方法

获取子进程status

具体代码实现

进程程序替换

替换原理

替换函数

命名理解

execl函数

​编辑 execv函数

execlp函数

execvp函数

 execle函数

execve/execvpe函数

总结


进程创建

fork函数初识

在linux中fork函数时非常重要的函数,它从已存在进程中创建一个新进程。新进程为子进程,而原进程为父进程。

#include <unistd.h>
pid_t fork(void);
返回值:自进程中返回0,父进程返回子进程id,出错返回-1

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

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

当一个进程调用fork之后,就有两个二进制代码相同的进程。而且它们都运行到相同的地方。但每个进程都将可以开始它们自己运行,看如下程序:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(void)
{
    pid_t pid;
    printf("Before: pid is %d\n", getpid());
    if ((pid=fork()) == -1)
        perror("fork()"),exit(1);
    printf("After:pid is %d, fork return %d\n", getpid(), pid);
    sleep(1);
    return 0;
}

运行结果如下:

这里看到了三行输出,一行before,两行after。进程7284先打印before消息,然后它有打印after。另一个after消息有7285打印的。注意到进程7285没有打印before,为什么呢?

如下图所示:

所以,fork之前父进程独立执行,fork之后,父子两个执行流分别执行。注意,fork之后,谁先执行完全由调度器决定。

为什么子进程只能执行的是fork的后续代码?

CPU中的eip程序计数器(也叫做pc指针)会保存当前正在执行指令的下一条指令,eip程序计数器会拷贝给子进程,子进程便从该eip所指向的代码处开始执行!

fork函数返回值

  • 子进程返回0
  • 父进程返回的是子进程的pid

写时拷贝

通常,父子代码共享,父子再不写入时,数据也是共享的,当任意一方试图写入,便以写时拷贝的方式各自一份副本,具体见下图:

为什么要写时拷贝?

  1. 父进程数据子进程不一定全用,即使使用也不一定全部写入,即可能造成空间浪费
  2. 只分离拷贝会被父子修改的数据,但从技术角度实现复杂
  3. fork时就将数据拷贝给子进程,会增加fork的内存和时间成本

因此,采用写时拷贝,虽然拷贝成本依旧存在,但是对此还采用延迟拷贝的策略,即只有使用内存时才真正分配给你,即使申请了内存但未立马使用,别的程序也能使用该内存

fork常规用法

  • 一个父进程希望复制自己,使父子进程同时执行不同的代码段。例如,父进程等待客户端请求,生成子进程来处理请求。
  • 一个进程要执行一个不同的程序。例如子进程从fork返回后,调用exec函数。

fork调用失败的原因

  • 系统中有太多的进程
  • 实际用户的进程数超过了限制

进程终止

进程退出场景

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

进程常见退出方法

正常终止(可以通过echo $?查看最近一次执行完毕时,对应进程的退出码):

  1. 从main返回
  2. 调用exit
  3. _exit

异常退出:

  • ctrl + c,信号终止

_exit函数

#include <unistd.h>
void _exit(int status);
参数:status 定义了进程的终止状态,父进程通过wait来获取该值
  • 说明:虽然status是int,但是仅有低8位可以被父进程所用。所以_exit(-1)时,在终端执行echo $?发现返回值是255。
  • 直接终止进程,不会有任何刷新操作

exit函数

#include <unistd.h>
void exit(int status);

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

  1. 执行用户通过atexit或on_exit定义的清理函数。
  2. 关闭所有打开的流,刷新缓冲区,所有的缓存数据均被写入
  3. 调用_exit

 实例:

int main()
{
    printf("hello");
    exit(0);
}

运行结果:

return退出

return是一种更常见的退出进程方法。执行return n等同于执行exit(n),因为调用main的运行时函数会将main的返回值当做exit的参数。

进程等待

进程等待必要性

  • 子进程退出,父进程如果不管不顾,就可能造成“僵尸进程”的问题,进而造成内存泄漏。
  • 进程一旦变成僵尸状态,就会变成了不可被杀死的进程,kill -9也无能为力,因为无法杀死一个已经死去的进程。
  • 我们需要知道,父进程派给子进程的任务完成的如何。如子进程运行完成,结果对还是不对,或者是否正常退出。
  • 父进程通过进程等待的方式,回收子进程资源,获取子进程退出信息

进程等待的方法

wait方法

#include<sys/types.h>
#include<sys/wait.h>
pid_t wait(int* status);
返回值:
成功返回被等待进程pid,失败返回-1。
参数:
输出型参数,获取子进程退出状态,不关心则可以设置成为NULL

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
    pid id = fork();
    if(id == 0)
    {
        while(1)
        {
            printf("I am child, pid:%d\n", getpid());
            sleep(1);
        }
    }
    else
    {
        printf("I am father, pid:%d\n", getpid());
        sleep(20);
        pid_t ret = wait(NULL);
        if(ret < 0)
        {
            printf("failed!\n");
        }
        else
        {
            printf("success, result:%d\n", ret);
        }
        sleep(20);
    }
    return 0;
}

运行该代码,并在第二个终端执行以下指令:

while :; do ps axj | head -1 && ps axj | grep test | grep -v grep; sleep 1; done

在第三个终端将child进程杀掉,此时查看第二个终端出现以下现象:

则说明我们成功将子进程给处理掉并解决了内存泄漏的问题。 

waitpid方法

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相等的子进程。
status:
WIFEXITED(status): 若为正常终止子进程返回的状态,则为真。(查看进程是否是正常退出)
WEXITSTATUS(status): 若WIFEXITED非零,提取子进程退出码。(查看进程的退出码)
options:
WNOHANG: 若pid指定的子进程没有结束,则waitpid()函数返回0,不予以等待。若正常结束,则返回该
子进程的ID。
0:阻塞等待
  • 如果子进程已经退出,调用wait/waitpid时,wait/waitpid会立即返回,并且0释放资源,获得子进程退出信息。
  • 如果在任意时刻调用wait/waitpid,子进程存在且正常运行,则进程可能阻塞。
  • 如果不存在该子进程,则立即出错返回。

获取子进程status

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

最低七位被信号码使用,第八位被用做core dump标志,次八位被退出码使用,一旦进程出现异常只关心退出信号,退出码没有任何意义

测试代码:

#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>

int main( void )
{
    pid_t pid;
    if ( (pid=fork()) == -1 )
        perror("fork"),exit(1);
    if ( pid == 0 ){
        sleep(20);

        exit(10);
    } else {
        int st;
        int ret = wait(&st);
        if (ret > 0 && (st & 0X7F) == 0){ // 正常退出
            printf("child exit code:%d\n", (st>>8)&0XFF);
        } else if(ret > 0) { // 异常退出
            printf("sig code : %d\n", st&0X7F );
        }
    }
}

 测试结果:

 因为是正常退出,所以打印出了退出码

具体代码实现

  • 进程的阻塞等待方式:
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(257);
    } else{
        int status = 0;
        pid_t ret = waitpid(-1, &status, 0);//阻塞式等待,等待5S
        printf("this is test for wait\n");
        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

  • 进程的非阻塞等待方式:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main()
{
    pid_t id = fork();
    if(id == 0)
    {
        while(1)
        {
            printf("I am child mypid is %d\n", getpid());
            sleep(1);
        }
        exit(10);
    }
    else if(id > 0)
    {
        int status = 0;
        while(1)
        {
            pid_t ret = waitpid(-1, &status, WNOHANG);
            if(ret > 0)
            {
                printf("wait success!mychild's pid is %d, exit single is %d, exit code is %d\n", ret, status&0x7F, (status>>8)&0xFF);
                break;
            }
            else if(ret == 0)
            {
                printf("I am father, I am doing other things and wait for child...\n");
                sleep(1);
            }
            else
            {
                printf("error!\n");
                break;
            }
        }
    }
    return 0;  
}
 

运行结果:

以上就是非阻塞轮询检测, 使用非阻塞轮询检测父进程可以在等待子进程返回的同时处理其他事务,不必在阻塞状态下等待子进程的返回

进程程序替换

替换原理

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

替换原理:将磁盘中程序加载进内存结构,重新建立页表映射,执行程序替换的程序重新建立该程序的映射。

进行程序替换后,父子进程彻底分离,并让子进程执行一个全新的程序。

替换函数

其实有六种以exec开头的函数,统称exec函数:

进程一旦替换成功,当前进程的代码和数据全部会被替换,若当前进程后续还有代码也不会执行,由于进程具有独立性,子进程执行程序替换不会影响父进程,进程替换时可以理解为代码和数据都发生了写时拷贝

#include <unistd.h>
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[]);

命名理解

这些函数原型看起来很容易混,但只要掌握了规律就很好记。

  • l(list) : 表示参数采用列表
  • v(vector) : 参数用数组
  • p(path) : 有p自动搜索环境变量PATH
  • e(env) : 表示自己维护环境变量

exec统一调用举例如下:

#include <unistd.h>
int main()
{
    char *const argv[] = {"ps", "-ef", NULL};
    char *const envp[] = {"PATH=/bin:/usr/bin", "TERM=console", NULL};
    execl("/bin/ps", "ps", "-ef", NULL);
    // 带p的,可以使用环境变量PATH,无需写全路径
    execlp("ps", "ps", "-ef", NULL);
    // 带e的,需要自己组装环境变量
    execle("ps", "ps", "-ef", NULL, envp);
    execv("/bin/ps", argv);
    // 带p的,可以使用环境变量PATH,无需写全路径
    execvp("ps", argv);
    // 带e的,需要自己组装环境变量
    execve("/bin/ps", argv, envp);
    exit(0);
}

PS:vim视图模式下批量使用注释的补充:

首先进入正常/普通/命令模式(Normal mode),然后使用ctrl+v进入视图模式,在这个模式下使用hjkl键位选择我们想要操作的区域,然后使用Caps lock进入大写模式使用i键位然后使用ESC键位,若需要将注释去掉则恢复成小写然后进入正常/普通/命令模式(Normal mode),然后再使用ctrl+v进入视图模式,在这个模式下使用hjkl键位选择我们想要操作的区域,然后使用d键位删除即可

execl函数

#include <unistd.h>
int execl(const char *path, const char *arg, ...);

根据man手册查看其使用方法,得知第一个参数是路径,后续的参数分别是指令和参数,若后续无参数则以NULL空指针结尾,所以以使用ls命令为例的其使用方式为:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
 
int main()
{
    printf("mypid is %d\n", getpid());
    pid_t id = fork();
    if(id == 0)
    {
        printf("I am child, mypid is %d\n", getpid());
        execl("/usr/bin/ls", "ls", "-a", "-l", NULL);                                                                                                     
        exit(1);                            
    }                                     
    int status = 0;                       
    int ret = waitpid(id, &status, 0);    
    if(ret == id)                         
    {                                     
        sleep(2);                           
        printf("wait successful!\n");       
    }                                     
    return 0;                             
}  

其输出结果为:

 execv函数

#include <unistd.h>
int execv(const char *path, char *const argv[]);

根据man手册查看其使用方法,得知第一个参数是路径,第二个参数是一个指针数组,这个指针数组中存储的每一个char*指针成员分别是指令和参数,和execl类似,只不过采用的是数组的方式存储起来了,所以以使用ls命令为例的其使用方式为:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
 
int main()
{
    printf("mypid is %d\n", getpid());
    pid_t id = fork();
    if(id == 0)
    {
        printf("I am child, mypid is %d\n", getpid());
        char *const argv_[] = {(char*)"ls", (char*)"-a", (char*)"-l", (char*)"-i", NULL};                                                                                                                                                                     
        execv("/usr/bin/top", argv_);
        exit(1);                            
    }                                     
    int status = 0;                       
    int ret = waitpid(id, &status, 0);    
    if(ret == id)                         
    {                                     
        sleep(2);                           
        printf("wait successful!\n");       
    }                                     
    return 0;                             
}  

其输出结果为:

execlp函数

#include <unistd.h>
int execlp(const char *file, const char *arg, ...);

根据man手册查看其使用方法,得知带p的,可以使用环境变量PATH,无需写全路径,但是这里虽然有两个相同的ls,但是不可以省略,第一个是供系统去环境变量中寻找ls,类似execl的第一个路径参数,第二个是指令,后续的参数则和execl一样,所以使用ls命令为例的其使用方式为:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
 
int main()
{
    printf("mypid is %d\n", getpid());
    pid_t id = fork();
    if(id == 0)
    {
        printf("I am child, mypid is %d\n", getpid());
        execlp("ls", "ls", "-a", "-l", "-i", NULL);
        exit(1);                            
    }                                     
    int status = 0;                       
    int ret = waitpid(id, &status, 0);    
    if(ret == id)                         
    {                                     
        sleep(2);                           
        printf("wait successful!\n");       
    }                                     
    return 0;                             
}  

其输出结果为:

execvp函数

#include <unistd.h>
int execvp(const char *file, char *const argv[]);

execlp函数和execv函数综合起来,所以使用ls命令为例的其使用方式为:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
 
int main()
{
    printf("mypid is %d\n", getpid());
    pid_t id = fork();
    if(id == 0)
    {
        printf("I am child, mypid is %d\n", getpid());
        char *const argv_[] = {(char*)"ls", (char*)"-a", (char*)"-l", (char*)"-i", NULL}; 
        execvp("ls", argv_);
        exit(1);                            
    }                                     
    int status = 0;                       
    int ret = waitpid(id, &status, 0);    
    if(ret == id)                         
    {                                     
        sleep(2);                           
        printf("wait successful!\n");       
    }                                     
    return 0;                             
}  

其输出结果为:

 execle函数

#include <unistd.h>
int execle(const char *path, const char *arg, ...,char *const envp[]);

PS:当我们想要使用同一个makefile创建多个不同的可执行程序时,可以采用以下方法:

makefile默认先生成all,all由于没有依赖方法,则makefile会将myexecl和mycmd的依赖关系推导出来并生成两个可执行程序

根据man手册查看其使用方法,得知带e的,需要自己组装环境变量,需要注意的是这里e:添加环境变量给目标进程是覆盖式的添加(即以PATH环境变量为例,当传入自己的环境变量时会覆盖掉目标进程的PATH环境变量,在shell上解决方法即使用export导入自己设置的环境变量并且传入系统的环境变量就都可以打印出来了),针对执行非系统级的程序,即需要我们自己传入路径或者是我们想调用其他的程序

//mycmd.cpp
#include <isotream>
#include <stdlib.h>
using namespace std;

int main()
{
    cout << "PATH:" << getenv("PATH") << endl;
    cout << "MYPATH:" << getenv("MYPATH") << endl;
    return 0;
}
//myexec.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
 
int main()
{
    printf("mypid is %d\n", getpid());
    pid_t id = fork();
    if(id == 0)
    {
        printf("I am child, mypid is %d\n", getpid());
        char* const env_[] = {(char*)"MYPATH=thisispath", NULL};
        execle("./mycmd", "mycmd", NULL, env_);//将会覆盖PATH环境变量
        exit(1);                            
    }                                     
    int status = 0;                       
    int ret = waitpid(id, &status, 0);    
    if(ret == id)                         
    {                                     
        sleep(2);                           
        printf("wait successful!\n");       
    }                                     
    return 0;                             
}  

其输出结果:

由于env_覆盖了PATH环境变量,导致PATH无法打印出来,后续MYPATH没有打印出来是因为getenv没有找到PATH环境变量而返回了NULL导致程序崩溃了,所以MYPATH没有打印出来,解决方法就是使用export导入MYPATH环境变量,然后再给mycmd程序传environ(即PATH环境变量)即可全部打印出来,就不会出现覆盖的问题了

execve/execvpe函数

int execve(const char *path, char *const argv[], char *const envp[]);

这个函数其实就是execle函数和execv函数的综合体,因此和execle函数及execv函数的使用方式极其相似

//mycmd.cpp
#include <isotream>
#include <stdlib.h>
using namespace std;

int main()
{
    cout << "PATH:" << getenv("PATH") << endl;
    cout << "MYPATH:" << getenv("MYPATH") << endl;
    return 0;
}
//myexec.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
 
int main()
{
    printf("mypid is %d\n", getpid());
    pid_t id = fork();
    if(id == 0)
    {
        printf("I am child, mypid is %d\n", getpid());

        char* const env_[] = {(char*)"MYPATH=thisispath", NULL};
        char* const argv_[] = {(char*)"mycmd", NULL};    
        execve("./mycmd", argv_, env_);//将会覆盖PATH环境变量
        exit(1);                            
    }                                     
    int status = 0;                       
    int ret = waitpid(id, &status, 0);    
    if(ret == id)                         
    {                                     
        sleep(2);                           
        printf("wait successful!\n");       
    }                                     
    return 0;                             
}  

运行结果:

发现情况和execle函数是一样,所以处理方式也和execle函数一样,看得出来其实在使用上execve函数=execle函数+execv函数,这里的execvpe参数和execve是一样的,由此可以推断出两者的使用方法是一模一样的,并且实践后发现确实如此:

所以在使用上可以将execvpe当execve使用即可。

总结

事实上,只有execve是真正的系统调用,其它五个函数最终都调用execve,所以execve在man手册第2节,其它函数在man手册第3节。这些函数之间的关系如下图所示。

下图exec函数族 一个完整的例子:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hiland.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值