首页 > 系统相关 >linux管理子进程

linux管理子进程

时间:2023-01-16 22:45:22浏览次数:37  
标签:status wpid sub 管理 process linux pid printf 进程

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\n", wpid, status);
    }else if(WIFEXITED(status)){
        printf("sub process %d WEXITSTATUS,status:%d\n", wpid, 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

 

标签:status,wpid,sub,管理,process,linux,pid,printf,进程
From: https://www.cnblogs.com/Netsharp/p/17056475.html

相关文章