LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 810|回复: 4

请教一段apue上的程序

[复制链接]
发表于 2005-8-12 09:50:16 | 显示全部楼层 |阅读模式
#include "global.h"
#include "err.h"

int glob=6;


int main()
{
        int var;
        pid_t pid;
        var = 88;
        printf("before vfork\n");

        if((pid=vfork())<0)
                err_sys("vfork error");

        else if(pid==0){
                glob++;
                var++;
                exit(0);//_exit(0);
        }
        /*parent*/
        printf("pid =%d,glob=%d, var=%d\n",getpid(),glob,var);
        exit(0);
}


    其中global.h 主要是一些头文件,err.h是书后给出的错误处理函数。
引用原书中的话,如果调用_exit(0)应该输出如下
$before vfork
pid =5422,glob=7, var=89
   如果调用exit(0)输出如下
$before vfork
   可是在我的机子上运行的结果,linux/2.6.8/Debian
  但是书中说应该的运行结果是(调用exit())
$before vfork
pid =5422,glob=7, var=89
   书中解释说:
   the child calls exit, which flushes and close all the standard I/O stream. This includes the standard output. Even though this is done by the child, it's done in the parent's address space, so all the standard I/O FILE objects that are modified are modified in the parent. When the parent calls printf later, standard output has been closed, and printf return -1.

   可是为什么在我的机子上运行结果都一样呢?哪位兄弟能给个解释!多谢!
发表于 2005-8-12 11:02:43 | 显示全部楼层
The function _exit is like exit(), but does not call any functions reg‐
       istered with the ANSI C atexit function, nor any registered signal han‐
       dlers. Whether it flushes standard I/O buffers  and  removes  temporary
       files  created  with  tmpfile(3)  is  implementation-dependent.  On the
       other hand, _exit does close open file descriptors, and this may  cause
       an unknown delay, waiting for pending output to finish. If the delay is
       undesired, it may be useful to call  functions  like  tcflush()  before
       calling _exit().  Whether any pending I/O is cancelled, and which pend‐
       ing I/O may be cancelled upon _exit(), is implementation-dependent.

我的理解是exit和_exit的不同之处就是_exit不执行用atexit注册的函数,其他和exit一样
回复 支持 反对

使用道具 举报

 楼主| 发表于 2005-8-13 11:04:42 | 显示全部楼层
可是问题还是没有讲明白啊,既然调用exit()函数时,要对标准输入输出流进行关闭,那么当子进程调用exit后,由于子进程和父进程共享的是相同的I/O流,那么父进程的也就关闭了。这样的话,
        printf("pid =%d,glob=%d, var=%d\n",getpid(),glob,var);在调用这句语句时I/O流已关闭,printf调用失败,就不应该有
        pid =5422,glob=7, var=89打印出来啊?
回复 支持 反对

使用道具 举报

发表于 2005-8-13 11:54:11 | 显示全部楼层
这是书中有问题的!再LINUX上也不是这样的!可能再FREEBSD上是的!再LINUX上exit()和_exit()结果也是一样的!
回复 支持 反对

使用道具 举报

 楼主| 发表于 2005-8-13 14:00:15 | 显示全部楼层
可能是跟系统有关吧!
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表