Ebram Shehata
Ebram Shehata

Reputation: 621

Get returned value of a child process without holding parent execution

I need to be able to get the returned value from a child process without having to hold the execution of the parent for it.

Notice the a runtime error could happen in the child process.

Here is my program that I'm trying to make:

//In parent process:
do
{
    read memory usage from /proc/ID/status
    if(max_child_memory_usage > memory_limit)
    {
        kill(proc, SIGKILL);
        puts("Memory limit exceeded");
        return -5; // MLE
    }
    getrusage(RUSAGE_SELF,&r_usage);
    check time and memory consumption
    if(memory limit exceeded || time limit exceeded)
    {
        kill(proc, SIGKILL);
        return fail;
    }
    /*
    need to catch the returned value from the child somehow with
    this loop working.
    Notice the a runtime error could happen in the child process.
    */
while(child is alive);

Upvotes: 1

Views: 580

Answers (2)

Nikhil Khatri
Nikhil Khatri

Reputation: 11

The solutions using the WNOHANG flag would work only if you need to check just once for the exit status of the child. If however you would like to procure the exit status when the child exits, no matter how late that is, a better solution is to set a signal handler for the SIGCHLD signal. When the child process terminates whether normally or abnormally, SIGCHLD will be sent to the parent process. Within this signal handler, you can call wait to reap the exit status of the child.

void child_exit_handler(int signo){

    int exit_status;

    int pid = wait(&exit_status);

    // Do things ...
}
// later in the code, before forking and creating the child
signal(SIGCHLD, child_exit_handler);

Depending on other semantics of your program, you may want to use waitpid instead. (SIGCHLD may also be called if the program was stopped, not terminated. The man page for wait(2) describes macros to check for this.)

Upvotes: 1

dbush
dbush

Reputation: 225344

The waitpid function has an option called WNOHANG which causes it to return immediately if the given child has not yet returned:

pid_t rval;
int status;
do {
    ...

    rval = waitpid(proc, &status, WNOHANG);
} while (rval == 0);

if (rval == proc) {
    if (WIFEXITED(status)) {
        printf("%d exited normal with status %d\n", WEXITSTATUS(status));
    } else {
        printf("%d exited abnormally\n");
    }
}

See the man page for waitpid for more details on checking various abnormal exit conditions.

Upvotes: 2

Related Questions