日期:2014-05-16  浏览次数:20551 次

<<unix/linux 编程实践教程>>程序问题
//8.4.c
#include<stdio.h>
#include<string.h>

main()
{
int fd;
int pid;
char msg1[]="Test 1 2 3 ..\n";
char msg2[]="Hello, hello\n";
if((fd=creat("testfile",0644))==-1)
return 0;
if(write(fd,msg1,strlen(msg1))==-1)
return 0;
if((pid=fork())==-1)
return 0;
if(write(fd,msg2,strlen(msg2))==-1)
return 0;
close(fd);
return 1;
}

//8.5.c
#include<stdio.h>
main()
{
FILE *fp;
int pid;
char msg1[]="Test 1 2 3 ..\n";
char msg2[]="Hello, hello\n";
if((fp=fopen("testfile2","w"))==NULL)
return 0;
fprintf(fp,"%s",msg1);
if((pid=fork())==-1)
return 0;
fprintf(fp,"%s",msg2);
fclose(fp);
return 1;
}

其中8.4.c的文件中的输出为:
Test 1 2 3 ..
Hello, hello
Hello, hello
而8.5.c的文件中的输出为:
Test 1 2 3 ..
Hello, hello
Test 1 2 3 ..
Hello, hello

请教大神求解 谢谢
编程 linux

------解决方案--------------------
write 不带缓存的系统调用,直接写入文件了
fprintf 带缓存,程序中没有fflush,子进程继承了缓存,就写入的一样了