简体   繁体   中英

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;
    }
}

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.

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