欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > 【Linux】自定义子进程(第十篇)

【Linux】自定义子进程(第十篇)

2025/5/1 13:58:35 来源:https://blog.csdn.net/abclui/article/details/141847437  浏览:    关键词:【Linux】自定义子进程(第十篇)

exec替换进程映像(vfork 要结合 exec使用)

1.execl函数

用这个函数可以把当前进程替换为一个新进程,且新进程与原进程有相同的PID。

在进程的创建上Unix采用了一个独特的方法,它将进程创建与加载一个新进程映象分离。这样的好处是有更多的余地对两种操作进行管理。

当我们创建了一个进程之后,通常将子进程替换成新的进程映象,这可以用exec系列的函数来进行。当然,exec系列的函数也可以将当前进程替换掉。

示例:

#include <stdio.h>
#include <unistd.h>
int main()
{
​pid_t pid = fork();if(pid ==0){execl("/bin/ls","ls","-al",NULL);printf("execl endl\n");  //会被覆盖}printf("process.....\n");return 0;
}
​

注意事项: 如果需要子进程执行自定义代码或者任务,需要在fork后,exec之前完成。

2.exec系列函数(execl、execlp、execle、execv、execvp)

头文件<unistd.h>

extern char **environ;

原型:

int execl(const char *path, const char *arg, ...);int execlp(const char *file, const char *arg, ...);int execv(const char *path, char *const argv[]);int execvp(const char *file, char *const argv[]);int execle(const char *path, const char *arg, ..., char * const envp[]);

参数:

path参数表示你要启动程序的名称包括路径名

arg参数表示启动程序所带的参数,一般第一个参数为要执行命令名,不是带路径且arg必须以NULL结束

返回值:成功返回0,失败返回-1

以上exec系列函数区别:

1,带l 的exec函数:execl,execlp,execle,表示后边的参数以可变参数的形式给出且都以一个空指针结束。

2,带 p 的exec函数:execlp,execvp,表示第一个参数path不用输入完整路径,只有给出命令名即可,它会在环境变量PATH当中查找命令

3,不带 l 的exec函数:execv,execvp表示命令所需的参数以char *arg[]形式给出且arg最后一个元素必须11

是NULL

4,带 e 的exec函数:execle表示,将环境变量传递给需要替换的进程

示例:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
​
int main(void)
{printf("entering main process---\n");execl("/bin/ls","ls","-l",NULL); // l 所有的参数需要以独立字符里的形式传入execlp("ls","ls","-l",NULL); //p 使用者无需填写程序位置,系统自动查找适配char* arg_array[] ={"ls","-al",NULL};execv("/bin/ls",arg_array); //v 所有参数封装到数组中,传入数组// execle("/bin/ls","ls","-al",NULL,arg_array); //e 允许exec重载时使用开发者自定义环境变量printf("exiting main process ----\n");return 0;
}
​

execle的用法示例:

execle.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>int main(int argc, char *argv[])
{char * const envp[] = {"AA=11", "BB=22", NULL};printf("Entering main ...\n");int ret;//ret =execl("./hello", "hello", NULL);ret =execle("./hello", "hello", NULL, envp);if(ret == -1)perror("execl error");printf("Exiting main ...\n");return 0;
}

hello.c

#include <unistd.h>
#include <stdio.h>
extern char** environ;  声明就能用 int main(void)
{printf("hello pid=%d\n", getpid());int i;for (i=0; environ[i]!=NULL; ++i){printf("%s\n", environ[i]);}return 0;
}

使用方法:

mytest@buka:~/mytest/fork$ vi execle.c
mytest@buka:~/mytest/fork$ gcc execle.c -o app
mytest@buka:~/mytest/fork$ vi hello.c
mytest@buka:~/mytest/fork$ gcc hello.c -o hello
mytest@buka:~/mytest/fork$ ./app
father process
mytest@buka:~/mytest/fork$ hello pid=18589
AA=aa
BB=bb
​

注意:NULL:哨兵节点,exec初始化加载参数到NULL结束,必须写,否则exec报错。(NULL不可以用0代替)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词