先看一个简单的程序, 如下:

 

#include <stdio.h>

int main()
{
	printf("hello");
	
	while(1)
	{
		NULL;
	}
	
	return 0;
}

     习惯在Windows下写代码的朋友, 自然会说, 肯定有hello打印啊。 但是, 在gcc下的结果为:

 

 

 [taoge@localhost learn_c]$ gcc test.c 
[taoge@localhost learn_c]$ ./a.out 
^C
[taoge@localhost learn_c]$ ^C
[taoge@localhost learn_c]$  
 
        我们没有看到hello的打印, 为什么呢? 原来是内存缓冲区在作怪, printf把字符串塞到了输出缓冲区, 而又没有遇到\n, 所以暂时并不输出到终端。 输出缓冲区实际上就是一块内存, 至于为什么引入输出缓冲区, 实际上也不难理解, 我就一句话:便于批量处理, 提高性能和效率。 得了吧。
 
 
        好, 我们看看程序:
#include <stdio.h>
#include <stdlib.h> // for exit

int main()
{
	printf("hello");
	
	exit(0);
}
       结果为:
 [taoge@localhost learn_c]$ gcc test.c 
[taoge@localhost learn_c]$ ./a.out 
hello[taoge@localhost learn_c]$  
 
       我们看到, 有hello的打印。
 
 
       好, 继续看程序:
#include <stdio.h>
#include <unistd.h> // for _exit

int main()
{
	printf("hello");
	
	_exit(0);
}
        结果为:
[taoge@localhost learn_c]$ gcc test.c 
[taoge@localhost learn_c]$ ./a.out 
[taoge@localhost learn_c]$ 
 
       我们看到, 没有hello的打印。 第二个程序和第三个程序的结果为什么不同呢? 原来: 调用_exit是直接退出进程, 而调用exit是先要处理一些其它内容(比如, 要把输出缓冲区中的一些是屎屎尿尿冲洗干净, 所以我们看见, hello被冲洗出来了), 然后再调用_exit退出进程.

 
 

 

 

 

 

 

 


本文转载:CSDN博客