Linux exec简介

exec系列函数简介

fork子进程之后,子进程要调用exec系列函数执行程序,这个调用用新程序替换了当前进程的正文段、数据段、堆段、栈段。

#include <unistd.h>

extern char **environ;
int execl(const char *path, const char *arg, ...);
int execle(const char *path, const char *arg, ..., char * const envp[]);
int execv(const char *path, char *const argv[]);

int execlp(const char *file, const char *arg, ...);
int execvp(const char *file, char *const argv[]);
int execvpe(const char *file, char *const argv[],char *const envp[]);

第一个参数为path的是需要加路径
第一个参数为filename的是在PATH环境变量中搜索

执行exec后,进程ID没有变。新程序从调用的子进程继承了下面属性:
进程ID和父进程ID
实际用户ID和实际组ID
附属组ID
进程组ID
回话ID
等等

下面写个程序,进行简单验证,代码也可以:github

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <sys/time.h>
#include <malloc.h>

int main(int argc, char **argv)
{
    pid_t pid;
    if((pid=fork())<0)
    {
        printf("fork error\r\n");
        return -1;
    }
    else if(pid == 0)
    {
        printf("child  pid = %ld\r\n",(long)getpid());
        printf("child  uid = %ld\r\n",(long)getuid());
        printf("child  gid = %ld\r\n",(long)getgid());
    //  execl("/bin/ls", "ls", "-l", (char *)0);
        execlp("ls", "ls", "-l", (char *)0);
    }
    else
    {
        int stat;
        pid_t pid=wait(&stat);
        printf("child terminate pid = %ld\r\n",(long)pid);
        printf("child terminate uid = %ld\r\n",(long)getuid());
        printf("child terminate gid = %ld\r\n",(long)getgid());
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值