sami younis
sami younis

Reputation: 1

is there an abnormal way to terminate a child process to get certain outputs in this code?

i'm new to operating systems and i found this code , and i don't understand why certain outputs like : abc , we can't get suppose we have this code in c :

    int main() 
{
    if(fork()==0)
        printf("a");
        else
        {
            printf("b");
            waitpid(-1);
        }
        printf("c");
    return 0;
}

waitpid() waits for a child process to terminate. can the child process be terminated in abnormal way ? so that we can have this outputs : abc, bc ?

Upvotes: 0

Views: 52

Answers (1)

Osinaga
Osinaga

Reputation: 71

according to at least the linux manpage for fork:

RETURN VALUE
       On success, the PID of the child process is returned in the parent, and
       0  is returned in the child.  On failure, -1 is returned in the parent,
       no child process is created, and errno is set appropriately.

so if your child program isn't ever created the entire output will be c for the parent process and nothing for the child process, because it never came to be.

Also it is possible that the parent process is killed before it can output a, or c, then you'll only get the child's output, bc. or maybe the parent is killed before it can even fork! there are lots of possibilities and with good timing (and some calls to the sleep function inbetween) you could probably reproduce them.

Upvotes: 0

Related Questions