首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 操作系统 > UNIXLINUX >

<<unix/linux 编程实践教程>>程序有关问题

2013-06-26 
unix/linux 编程实践教程程序问题//8.4.c#includestdio.h#includestring.hmain(){int fdint pid

<<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,子进程继承了缓存,就写入的一样了

热点排行