Linux进程控制--进程替换

Linux进程替换

使用fork创建的进程和父进程运行的相同的程序(执行不同的代码分支),子进程需要运行其他程序需要通过exec函数进行进程替换运行另一个程序。

替换函数

exec函数总共有六个

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[]);

这六个函数中execve是系统调用其他五个函数实现均为调用execve的库函数
参数:
函数名中含l(list) 指参数采用列表(使用罗列的方式传参并且以NULL结束)
函数名中含p(path) 指函数利用程序的PATH环境变量查找子程序
函数名中含v(vector) 参数接收到一个以NULL结尾的字符串数组的指针
函数名中含e(env) 指自己维护环境变量
返回值:
成功将不再返回,开始执行新的程序(从启动代码开始执行)
失败返回-1

函数的使用

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

int main()
{
    pid_t pid = fork();
    if(pid == -1)
    {
        perror("creat child process failure");
        exit(-1);
    }
    else if(pid == 0)
    {
        printf("\n");
        if(execl("/bin/ps", "ps","-ef", NULL) == -1)
        {
        	perror("execl error");
		}
    }
    else
    {
        printf("this is parent\n");
    }
    return 0;
}

在这里插入图片描述

execv函数

#include <stdio.h>
#include <unistd.h>
int main()
{
    printf("before execv\n");
    char *argv[] = {"ps", "-ef", NULL};
    if(execv("/bin/ps", argv) < 0)
    {
        printf("execv error");
    }
    return 0;
}

在这里插入图片描述

execvp函数

#include <stdio.h>
#include <unistd.h>
int main()
{
    printf("before execvp\n");
    char *argv[] = {"ps", "-ef", NULL};
    if(execvp("ps", argv) < 0)
    {
        printf("execvp error");
    }
    return 0;
}

在这里插入图片描述

execlp函数

#include <stdio.h>
#include <unistd.h>
int main()
{
    printf("before execlp\n");
    if(execlp("ps", "ps", "-ef", NULL) < 0)
    {
        printf("execlp error");
    }
    return 0;
}

在这里插入图片描述

execle函数

扫描二维码关注公众号,回复: 4128686 查看本文章
//print程序代码
#include <stdio.h>
int main(int argc, char * argv[], char * envp[])
{
    int i = 0;
    while(envp[i] != NULL)
    {
        printf("%s\n", envp[i++]);
    }
    return 0;
}
#include <stdio.h>
#include <unistd.h>
int main()
{
    printf("before execle\n");
    char * envp[] = {"PATH = /bin:/usr/bin", NULL};
    if(execle("./print", NULL, envp) < 0)
    {
        printf("execle error");
    }
    return 0;
}

在这里插入图片描述

在这里要解释的是,如果不使用execle 和execve 函数程序的环境变量均继承父进程,当使用这两个函数时程序的环境变量由自己组织;

猜你喜欢

转载自blog.csdn.net/Jocker_D/article/details/83784088