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 2023-01-16 22:34  Netsharp  阅读(63)  评论(0编辑  收藏  举报

导航