Вопрос

I googled for answer but all the threads I found seemed to suggest using an alternative way to terminate a child process: the _Exit() function.

I wonder if using "return 0;" truly terminate the child process? I tested that in my program (I have waitpid() in the parent process to catch the termination of the child process), and it seemed to work just fine.

So can someone please confirm on this question? Does a return statement truly terminate a process like the exit function or it simply sends a signal indicating the calling process is "done" while the process is actually still running?

Thanks in advance, Dan

Sample Code:

pid = fork()

if (pid == 0) // child process
{
   // do some operation
   return 0; // Does this terminate the child process?
}
else if (pid > 0) // parent process
{
   waitpid(pid, &status, 0);
   // do some operation
}
Это было полезно?

Решение

Using the return statement inside the main function will immediately terminate the process and return the value specified. The process is terminated completely.

int main (int argc, char **argv) {
    return 2;
    return 1;
}

This program never reaches the second return statement, and the value 2 is returned to the caller.

EDIT - Example from when the fork happens inside another function

However if the return statement is not inside the main function, the child process will not terminate until it has reached down into main() again. The code below will output:

Child process will now return 2
Child process returns to parent process: 2
Parent process will now return 1

Code (tested on Linux):

pid_t pid;

int fork_function() {
    pid = fork();
    if (pid == 0) {
        return 2;
    }
    else {
        int status;
        waitpid (pid, &status, 0); 
        printf ("Child process returns to parent process: %i\n", WEXITSTATUS(status));
    }
    return 1;
}

int main (int argc, char **argv) {
    int result = fork_function();
    if (pid == 0) {
        printf ("Child process will now return %i\n", result);
    }
    else {
        printf ("Parent process will now return %i\n", result);
    }
    return result;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top