In c language, what's the difference between return x and exit ( x ) in the main function.

115 5

Most recently read APUE, APUE 7.3, the main function return is equivalent

exit(main(argc, argv))

But there was a problem in the practice program 8 -2.

Execution of the following program is core-dump.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int glob = 6;
int
main(void)
{
 int var;
 pid_t pid;
 var = 88;
 printf("before vforkn");
 if ((pid = vfork()) <0) {
 printf("vfork error");
 exit(-1);
 } else if (pid == 0) {
/* 子进程 */
 glob++;
 var++;
 return 0;
//exit(0);
 }
 printf("pid=%d, glob=%d, var=%dn", getpid(), glob, var);
 return 0;
//exit(0);
}

But instead, change return to exit.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int glob = 6;
int
main(void)
{
 int var;
 pid_t pid;
 var = 88;
 printf("before vforkn");
 if ((pid = vfork()) <0) {
 printf("vfork error");
 exit(-1);
 } else if (pid == 0) {
/* 子进程 */
 glob++;
 var++;
//return 0;
 exit(0);
 }
 printf("pid=%d, glob=%d, var=%dn", getpid(), glob, var);
//return 0;
 exit(0);
} 

What's the reason why the first program will be core-dump.

4 Answers

114 4

Extract a section of the c language design - modern method & 9.5 chapter

The difference between the return statement and the exit function is: No matter which function call exit function causes the program to terminate, the return statement causes the program to terminate only if it's called by the main function.

Ps: your code seems to have a problem ( I put a count on printf )
Printf ("pid = % d, glob = % d, var = % d -> % d <--n", getpid ( ), glob, var, + + i );"
When you use return 0, the result is that:

..... .
before vfork
pid=5101, glob=31853, var=-232083051 ->31847<--
before vfork
pid=5101, glob=31854, var=-232083051 ->31848<--
before vfork
pid=5101, glob=31855, var=-232083051 ->31849<--
before vfork

And stopped.

And when you use exit 0, this is:

straysh Learning]$./a.out 
before vfork
pid=5145, glob=7, var=4195680 ->1<--
...