When does a process terminate in UNIX

exitprocess

At which moment a process in Unix is terminated? Is it necessary a command such as exit(0) or return 0 to be written in a program to terminate a process?
My question is provoked by the following code:

pid_t pid=fork();
if(pid < 0)
{
         perror("Fork error\n");
         return 1;  
}
else if (pid==0) /* child */
{
        printf("CHILD My pid is:%d\n",getpid());
}
else /* parrent */
{
         wait(NULL);
         exit(0);
}

In this example, in the child we do NOT call exit(0)(so I think we do NOT terminate the process) and in the parent we call wait(NULL)(so we should wait for the process to end). The program terminates, so logically at one moment the child process ends. Can you explain me when does the child process terminate? If the child terminates after

else if (pid==0) /* child */
    {
            printf("CHILD My pid is:%d\n",getpid());
    }/* Probably the child process terminates here but then what is the point of using exit(0) */

, well then what is the point of using exit(0)?

Best Answer

A C program will end in one of three conditions:

  1. The program returns from the main function. If the return value is 0, that indicates success, otherwise the return value is the exit state. C99 also allows (but discourages) a main function with a void return type, where returning from main has the same semantics as returning 0 from a main with int return type.
  2. The program returns one of the exit functions: exit, _exit, or the new quick_exit function in C11. These functions all do not return and all have the effect of terminating the program, but what they actually do differs (e.g., quick_exit flushes buffers but does not run honour atexit calls).
  3. The OS kills the program in some way, e.g., because the program does something it is not allowed to do.