linux管理子进程
linux子进程的管理需要fork()与exec()连用,下面的例子app1是主进程,app2是子进程
app1.c
#include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> int main() { pid_t subid = vfork(); pid_t pid = getpid(); if (subid == 0) { printf("sub pid : %d\n", pid); execlp("./app2", "arg1", "arg2", NULL); } else { int status; pid_t wpid = waitpid(subid, &status, WUNTRACED); // WNOHANG WUNTRACED WCONTINUED if (WIFEXITED(status)) { printf("sub process %d 正常退出,status:%d, exit code: %d\n", wpid, status, WEXITSTATUS(status)); } else if (WTERMSIG(status)) { printf("sub process %d WTERMSIG,status:%d\n", wpid, status); } else if (WSTOPSIG(status)) { printf("sub process %d WSTOPSIG,status:%d\n", wpid, status); } else if (WIFSIGNALED(status)) { printf("sub process %d WIFSIGNALED,status:%d\n", wpid, status); } else if (WIFSTOPPED(status)) { printf("sub process %d WIFSTOPPED,status:%d\n", wpid, status); } else if (WCOREDUMP(status)) { printf("sub process %d WCOREDUMP,status:%d\n", wpid, status); } else { printf("sub process %d,status:%d\n", wpid, status); } } return 0; }
app2.c
#include "stdio.h" #include "unistd.h" int main(int argc, char** argv) { pid_t pid = getpid(); printf("app2 pid : %d\n", pid); for (int i = 0; i < argc; i++) { printf("arg[%d]:%s\n", i, argv[i]); } for (int i = 0; i < 3; i++) { printf("app2 %d: %d\n",i, pid); sleep(1); } return 10; }
执行结果
$ ./app1 sub pid : 5211 app2 pid : 5211 arg[0]:arg1 arg[1]:arg2 app2 0: 5211 app2 1: 5211 app2 2: 5211 sub process 5211 正常退出,status:2560, exit code: 10
作者 :秋时
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述