0

Normally, if I want the exit status of a child I just do:

int pid=fork();

switch(pid)
{
case -1:
/*Error treatment*/
exit(1);

case 0:
/*Child part*/
exit(0);

default:
waitpid(pid,&status,0)
WIFEXITED(status);
}

Then I have the exit status on status.

The problem is that, when the process is on background I obviously don't want to do waitpid() so I don't know how to store the exit value in status.

Thanks for the help!

walter
  • 193
  • 9
  • 1
    `waitpid` will wait for the child to exit whether it's in the background or not. – dbush May 19 '21 at 12:25
  • 4
    Either use the `WNOHANG` option for `waitpid` to peridically poll the status. Or catch the `SIGCHLD` signal to get a "notification" when a child process changes state. – Some programmer dude May 19 '21 at 12:26
  • @dbush That's the thing, I DON'T want to do waitpid because, since I want to the the child process on bg, I don't want to wait for it. – walter May 19 '21 at 12:27
  • 3
    @walter, that's why you have to use `WNOHANG`. Read the man page. – Devolus May 19 '21 at 12:28
  • @Devolus It didn't work, what this is doing is nit wait and always return 0 as exit status. What I need is for the program to continue and when the child on background finishes, to have that exit status in status. Now, status is 0 no matter what the child does. – walter May 19 '21 at 12:46
  • If it's running in the background, it doesn't exit so there is no exit status. Please [edit] your question to clarify what you mean. – Ulrich Eckhardt May 19 '21 at 13:08

1 Answers1

2

After the child process has been spawned, the parent will need to call waitpid periodically with the WNOHANG flag. Using this flag will cause the function to return immediately, after which you need to check the status to see if the process actually exited or not.

For example:

int child_done;
do {
    // do something useful

    child_done=0;
    if (waitpid(pid,&status,WNOHANG) > 0) {
        if (WIFEXITED(status)) {
            printf("child exited with status %d\n", WEXITSTATUS(status));
            child_done = 1;
        }
        if (WIFSIGNALED(status)) {
            printf("child terminated by signal %d\n", WTERMSIG(status));
            child_done = 1;
        }
    }
} while (!child_done);
dbush
  • 205,898
  • 23
  • 218
  • 273