SantaXL
SantaXL

Reputation: 674

Ending child process with return 0

Is return 0 in case 0 the correct choice? In other words, does return 0 call the _exit() function? Or maybe it calls exit(), hence this code is unsafe?

#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>

int main(void)
{
    printf("hello_fork! (PID=%lu)\n", (unsigned long)getpid());
    pid_t pid = fork();
    switch(pid){
        case -1: perror("fork"); return 1;

        case 0: printf("child: PID=%lu\n", (unsigned long)getpid());
        return 0;

        default: printf("parent: PID=%lu\n\n", (unsigned long)getpid()); 
        if(wait(NULL)<0) 
            perror("wait");
        printf("THE END\n");
        return 0;
    }
}

Upvotes: 3

Views: 209

Answers (1)

dbush
dbush

Reputation: 225537

Calling return from the main function is equivalent to calling exit.

From section 5.1.2.2.3 of the C standard:

If the return type of the main function is a type compatible with int, a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument

Because you're exiting from a child process, you should explicitly call _exit instead.

Upvotes: 4

Related Questions