C语言中exit和return的区别
今天在看《TCP/IP网络编程》的第10章“基于多任务的并发服务器”时发现,作者在子进程中使用了return 0来结束,而我之前在网上找的tcp socket示例则是使用了exit(0)来结束。那么return和exit有什么区别吗?
在 https://stackoverflow.com/questions/3463551/what-is-the-difference-between-exit-and-return 找到了几个我觉得看得懂的解释
Example with return:
#include <stdio.h>
void f(){
printf("Executing f\n");
return;
}
int main(){
f();
printf("Back from f\n");
}
If you execute this program it prints:
Executing f
Back from f
Another example for exit():
#include <stdio.h>
#include <stdlib.h>
void f(){
printf("Executing f\n");
exit(0);
}
int main(){
f();
printf("Back from f\n");
}
If you execute this program it prints:
Executing f
I wrote two programs:
int main(){return 0;}
and
#include <stdlib.h>
int main(){exit(0)}
After executing gcc -S -O1. Here what I found watching at assembly (only important parts):
main:
movl $0, %eax /* setting return value */
ret /* return from main */
and
main:
subq $8, %rsp /* reserving some space */
movl $0, %edi /* setting return value */
call exit /* calling exit function */
/* magic and machine specific wizardry after this call */
So my conclusion is: use return when you can, and exit() when you need.