系统调用 execve
main.c
#include <stdio.h> #include <unistd.h> #include <sys/wait.h> char * argv[]={ "arg1","arg2", NULL }; char * envp[] = { "PATH=/bin", "HOME=/root", NULL }; int main() { printf("main pid = %d\n", getpid()); int pid; if(!(pid=fork())) { printf("execve pid = %d\n", getpid()); // 执行hello不创建新进程 hello的pid和这个子进程pid相同 execve("./hello",argv,envp); } while(pid != wait(NULL)) /* do nothing */; printf("main end\n"); return 0; }
hello.c
#include <stdio.h> #include <unistd.h> int main(int argc, char **argv, char **envp) { printf("hello program start\n"); pid_t pid = getpid(); printf("helllo pid = %d\n", pid); int i; for(i=0;i<argc;i++) printf("argv: %s\n",argv[i]); while (*envp != NULL) printf("arge: %s\n",*envp++); printf("hello program end\n"); return 0; }
编译运行
gcc mian.c -o main gcc hello.c -o hello ./main
执行结果
main pid = 4408 execve pid = 4410 hello program start helllo pid = 4410 argv: arg1 argv: arg2 arge: PATH=/bin arge: HOME=/root hello program end main end
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具