简体   繁体   中英

Checking if a process has terminated in C

I got stuck trying to come up with a function in C.

Basically what it's supposed to do is: it first checks if a specific process has terminated. If it has, it increments the returned value of the terminated process into a list. If it hasn't terminated, it waits until it does.

I've read the manual (man wait) and done research on the subject, but found it very confusing to understand this.

I have two pre-existent lists:

  • child_pids, which contain all the child's processes pid's.
  • child_return_values, which is the list where the return values should be incremented.

I also have a constant, child_pids_size, which is the size of the list child_pids.

Here's what i've done so far:

void wait_process(){

    int i, child_state, value;
    pid_t child_pid, rc_pid;

    for(i = 0; i < child_pids_size; i++){

    child_pid = child_pids[i];

    rc_pid = waitpid(child_pid,&child_state,0);

    if(rc_pid > 0){

        //if the process terminated
        if (WIFEXITED(child_state)){


        //it increments the position of the process
        // in the list with the returned value of waitpid
        value = child_return_values[i];
        value = value + rc_pid;
        child_return_values[i] = value;

        }

        else{
        perror("An error occurred!");
        exit(1);

        }

    }


}


}

I suppose "the returned value of the terminated process" is referring to the exit value of the child process (ie the value used by the process while calling exit()).

To obtain it you may use the WEXITSTATUS() macro using child_state as a parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM