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
作者 :秋时
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。
浙公网安备 33010602011771号