文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>apue8-1笔记

apue8-1笔记

时间:2006-04-11  来源:suseat

#include<sys/types.h>
#include"ourhdr.h"
int glob=6;
char buf[]="a write to stdout\n";
int main(void)
{
    int var;
    pid_t pid;
    var=88;
    if(write(STDOUT_FILENO,buf,sizeof(buf)-1)!=sizeof(buf)-1)
    {
    err_sys("write error!");
    }
    printf("before fork\n");
    if((pid=fork())<0)
    err_sys("fork error");
    else if(pid==0)
    {
      glob++;
      var++;
    }
    else
      sleep(2);
    printf("pid=%d,glob=%d,var=%d\n",pid,glob,var);
    exit(0);
}
编译后执行如下:
george@suseat:~/practices/apue/c8> ./e1
a write to stdout
before fork
pid=0,glob=7,var=89
pid=6295,glob=6,var=88

george@suseat:~/practices/apue/c8> ./e1 >test
george@suseat:~/practices/apue/c8> cat test
a write to stdout
before fork
pid=0,glob=7,var=89
before fork
pid=6299,glob=6,var=88

可以发现以上得到的结果稍微有所不同,不同之处在于第二个例子多了一个'before fork'解释如下:
stand out is line buffered if it's connected to a terminal device(也就是行缓冲,如果输出一行,那么就缓冲就被flush掉),otherwise it's fully buffered.when we run the program interactively(也就是在console直接执行程序,此时的输出为stand output)we get only a single copy of the printf line,because the stand output buffer is flushed by the new line.

but when we redirect the stand output to a file,we get a copy of printf line.what happened in the second case is that the printf before the fork is called once,but the line remains in the buffer when fork is called.this buffer is then copied in to the child,when the parent's data space is copied to the child.

而对于在exit(0)前的printf,由于它只是将变量的数据拷入bufferr.所以和以上的情况不同.

对以上的例子进行改变:
将printf("before fork\n") 改为printf("before fork"),编译后运行
george@suseat:~/practices/apue/c8> ./e1
a write to stdout
before forkpid=0,glob=7,var=89
before forkpid=7079,glob=6,var=88
george@suseat:~/practices/apue/c8> ./e1 >test
george@suseat:~/practices/apue/c8> cat test
a write to stdout
before forkpid=0,glob=7,var=89
before forkpid=7083,glob=6,var=88
george@suseat:~/practices/apue/c8>    
此时可以发现,由于printf("before fork")没有换行,所以buffer并没有被flush掉.
相关阅读 更多 +
排行榜 更多 +
宝宝切水果安卓版

宝宝切水果安卓版

休闲益智 下载
儿童脑筋急转弯

儿童脑筋急转弯

休闲益智 下载
袭击现场2

袭击现场2

飞行射击 下载