首页 > 解决方案 > 如何检查正在运行的进程?

问题描述

假设我使用 fork 两次来获取两个子进程。然后,我想根据正在运行的进程以不同的方式执行 3 个进程(包括父进程)。这将如何在 c 语言中完成?以下工作是否有效:假设 PID1 是孩子 1 的进程 ID,类似地 PID2 是孩子 2,然后:我首先使用以下方法创建了两个孩子:

    pid1 = fork();
    if(pid1 == 0){
       PID1=getpid();
    }
    if(pid1 > 0){
       pid2 = fork();
       if(pid2 > 0){
          printf("\nParent ProcessL %d\n",getpid());
       }
       else if(pid2 == 0){
          PID2=getpid();
       }
     }
-----------------------------------------------------
further down in my code:

    while(/*true for a certain time*/){
       if (PID1==getpid()){
           //execute the code for child 1
       } else if (PID2==getpid()){
           // execute code for child 2
       } else {
           // execute the code for the parent
    }

顺便说一句,进程是随机运行还是按顺序运行(每个进程的时间固定)?

标签: cforkparent-child

解决方案


不会因为孩子中的pid返回值是.fork()0

实现目标的最简单方法是在每个fork().

pit_t PID1, PID2;
if(0>(PID1=fork()) {/*handle error*/}
if(!PID1) _exit(code_for_child1());

if(0>(PID2=fork()) {/*handle error*/}
if(!PID2) _exit(code_for_child2());

/*continue the parent's work*/

推荐阅读