exec函数记录

内容分享4天前发布
3 0 0

exec简介:

exec家族的函数,用来运行新的进程替换当前的进程。执行后,新进程加载到内存,父进程的静态变量在新的进程中当然是不可见。新进程可以继承父进程的句柄和环境变量,用户组。

示例

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

int g_value = 0;
int main(int argc, char **argv) 
{
    if (argc > 1 && strcmp(argv[1], "child") == 0) {
        printf("child g_value = %d
", g_value);
        return 0;
    }
    g_value = 1;
    printf("father g_value = %d
", g_value);
    int fd = open("/root/source/test.txt", O_RDWR);
    printf("father fd = %d
", fd);
    dup2(fd, 1);
    close(fd);
    execl("/root/source/cmd", "cmd", "child", NULL);
    printf("run child failed
");
    return 0;
}

如上代码编译一个cmd的二进制,执行cmd命令,
1、父进程将g_value 赋值为1,子进程中g_value 依然为0,子进程不会继承父进程的变量。
2、将标准输出的句柄绑定到/root/source/test.txt句柄。子进程的句柄依然指向/root/source/test.txt,子进程可以继承父进程的句柄。

root@yisu-66a113137e504:~/source# ./cmd
father g_value = 1
father fd = 3
root@yisu-66a113137e504:~/source# 
root@yisu-66a113137e504:~/source# cat test.txt 
child g_value = 0

这里顺带提一下fork,fork功能是创建一个新的进程,子进程获得父进程代码段和数据段的副本(虽然在现代系统中,一般使用写时复制技术来优化内存使用)。子进程继承父进程的资源限制(如文件大小限制、CPU 时间限制等)。
fork和execv的组合可实现子进程的管理,如fork创建一个新的进程,设置它的uid,gid后,再执行execv切换新进程替换当前进程。

android service启动

android service启动,使用到了fork 和 execv:

Result<void> Service::Start() {
    //....
    pid = fork();
   if (pid == 0) {
         RunService(...); // 其中执行 execv 加载新的程序,并设
   }
}

© 版权声明

相关文章

暂无评论

none
暂无评论...