当前位置: 技术问答>linux和unix
frok()后的文件描述符共享问题
来源: 互联网 发布时间:2016-08-09
本文导语: 刚在书上看到一个有关fork的文件描述符问题,看下代码吧,很简短的int main() { pid_t pid; char *message; int n=6; int length; message = "messagefromthestdoutn"; length = strlen(message); // write(STDOUT_FILENO,message,strlen(message)); printf("st...
刚在书上看到一个有关fork的文件描述符问题,看下代码吧,很简短的
gcc fork.c -o a.out后
问题在于我直接执行./a.out后得到预料的
starting........
This is the child
:pid= 8396 length=21
this is the father
:pid= 8395 length=21
但是当我执行./a.out > temp 然后cat temp后怎么temp里的内容是:
starting........
This is the child
:pid= 8398 length=21
starting........ //多出了一个start....呢
this is the father
:pid= 8397 length=21
怎么会多一行呢? 原因在哪呢? 我预料的temp里的内容应该没那行的,谢谢指教
int main()
{
pid_t pid;
char *message;
int n=6;
int length;
message = "messagefromthestdoutn";
length = strlen(message);
// write(STDOUT_FILENO,message,strlen(message));
printf("starting........n");
pid = fork();
switch(pid)
{
case -1:
printf("errorn");
case 0:
message = "This is the childn";
n++;
break;
default:
message = "this is the fathern";
n--;
sleep(2);
break;
}
printf("%s:pid= %d length=%dn",message,getpid(),length);
return;
}
gcc fork.c -o a.out后
问题在于我直接执行./a.out后得到预料的
starting........
This is the child
:pid= 8396 length=21
this is the father
:pid= 8395 length=21
但是当我执行./a.out > temp 然后cat temp后怎么temp里的内容是:
starting........
This is the child
:pid= 8398 length=21
starting........ //多出了一个start....呢
this is the father
:pid= 8397 length=21
怎么会多一行呢? 原因在哪呢? 我预料的temp里的内容应该没那行的,谢谢指教
|
fork出的子进程完全复制父进程的地址空间,完全是父进程的副本。对于终端输出, 标准输出指定的是行缓冲,所以printf一遇到n就输出了。然后fork出的子进程就没有starting......。如果一开始重定向到文件,标准输出采用的是全缓冲,遇到n也不会输出到文件,然后fork出的子进程缓冲区中当然也有原来的内容。
|
对于终端是行缓冲,对于普通文件是全缓冲吧
|
fork()后,子进程会复制一遍父进程的进程信息,由于fork()前父进程缓冲中有信息(starting。。。),fork()后子进程中的缓冲中也会有同样的信息,当你重定向的时候,父子进程都会输出同样的starting信息
|
printf("starting........n");
这句后面加上
fflush(stdout);
这句后面加上
fflush(stdout);
|
正解,重定向以后标准输出不再是行缓冲的。"n"并不会刷新标准输出。
./a.out | cat也会输出两次 "start...."
用fflush(stdout);强制刷新标准输出,就可以只输出一次了。
您可能感兴趣的文章:
本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。