wgqjjq
_exit函数的特殊作用吗?
[root@localhost demo]# cat fork.c
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
int main(void)
{
pid_t child;
if(!(child=fork()))
{
printf (" in child ");
_exit(0);
}
printf("/n prient pid -- child pid %d/n",child);
return 0;
}
编译后执行,没有显示[color=Red]in child [/color]这句
[root@localhost demo]# ./a.out
prient pid -- child pid 3465
而在printf (" in child ");改成printf (" /nin child /n");后,可以显示
[root@localhost demo]# ./a.out
in child
prient pid -- child pid 3465
请教大家,为什么不能显示,难道是_exit函数的作用?还有资料上说fork()返回值是随机的,但我试了很多边,都是先打印子进程,再打印父进程,难道是平台的缘故?(我用的是AS 4)??
kissGNU
[quote]原帖由 [i]wgqjjq[/i] 于 2008-6-15 19:33 发表 [url=http://linux.chinaunix.net/bbs/redirect.php?goto=findpost&pid=6613575&ptid=1010864][img]http://linux.chinaunix.net/bbs/images/common/back.gif[/img][/url]
“好像先执行父进程还是子进程,顺序不是固定的” ,这个我当然知道,但在AS4平台实践了多次,都是先打印子进程,再打印父进程,所以有点郁闷(没有得到想像的结果) [/quote]
纯属偶然,呵呵,这和系统负载、体系结构有关,不能简单地说子进程一定比父进程先执行。
另外printf()如果不是以/n结束,就不会立即在屏幕打印,存放在缓冲区中,直到缓冲区满或者下一个遇到/n或者被强制fflush()才会输出。
__exit()直接退出,return()会进行一些缓冲区输出操作。
MMMIX
[quote]原帖由 [i]wgqjjq[/i] 于 2008-6-15 19:07 发表 [url=http://linux.chinaunix.net/bbs/redirect.php?goto=findpost&pid=6613563&ptid=1010864][img]http://linux.chinaunix.net/bbs/images/common/back.gif[/img][/url]
感谢楼上两位的回复,但你们还是没有明白我问的问题,为什么加了两个“/n”之后就可以显示in child ,也许我的标题让大家误解了 [/quote]
翻下 apue2 中关于缓冲模式的介绍也许有帮助。