exec函数族

2024-11-08  本文已影响0人  锈色的栅栏

在进程中 启动另一个进程。

#include  <unistd.h>
extern char **environ;
int execl(const char *path, const char *arg, .../* (char *) NULL */);
int execlp(const char *file,cconst char *arg, ... /* (char *) NULL */);
int execle(const char *path, const char *arg, .../*, (char *) NULL, char * const envp[]*/);
int execv(const char *path, char *const argv[]);
int execvp(const char *file, char *const argv[]);
int execvpe(const char *file, char *const argv[], char *const envp[]);
int execve(const char *filename, char *const argv[], char *const envp[]);

函数中有l(list)表明使用列表方式传参,函数中有v(vector)表明使用指针数组传参。
函数中有p(path)表明 到系统环境中 找可执行性文件
函数中有e(evn) 表明exec可以使用环境变量值

execl(可执行文件位置,可执行文件名,可执行文件的选项,以NULL结尾);

一个进程调用exec后,除了进程ID,进程还保留了下列特征不变: 父进程号 进程组号 控制终端 根目录 当前工作目录 进程信号屏蔽集 未处理信号 ...

vfork和exec配合使用

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

int main(int argc,char const*argv[]){
    int num = 10;
    //vfork创建子进程
    pid_t pid = vfork();
    if (pid == 0) //子进程
    {
        //子进程负责启动起到程序
        sleep(3);
        execlp("ls", "ls", "‐a", "‐l", "‐h", NULL);
        //显示退出
        _exit(‐1);
    }
    else if (pid > 0) //父进程
     {
        //父进程运行自己的程序
        int i = 0;
        for (; i < 5; i++)
        {
            printf("父进程%d中的i=%d\n", getpid(), i);
            sleep(1);
        }
    }
    return 0;
}

上一篇 下一篇

猜你喜欢

热点阅读