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

复制代码

 

posted on   Netsharp  阅读(67)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述

导航

统计

点击右上角即可分享
微信分享提示