日期:2014-05-16 浏览次数:20841 次
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int 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;
}
Test 1 2 3 .. Hello, hello Hello, hello
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
int pid;
char msg1[]="Test 1 2 3 ...";
char msg2[]="Hello, hello";
if((fp=fopen("testfile2","w"))==NULL)
return 0;
fprintf(fp,"%s pid:%d\n",msg1,getpid());
if((pid=fork())==-1)
return 0;
fprintf(fp,"%s pid:%d\n",msg2,getpid());
fclose(fp);
return 1;
}
Test 1 2 3 ... pid:8795 Hello, hello pid:8795 Test 1 2 3 ... pid:8795 Hello, hello pid:8796
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
int pid;
char msg1[]="Test 1 2 3 ...";
char msg2[]="Hello, hello";
if((fp=fopen("testfile2","w"))==NULL)
return 0;
fprintf(fp,"%s pid:%d\n",msg1,getpid());
fflush(fp); //这样就好了
if((pid=fork())==-1)
return 0;
fprintf(fp,"%s pid:%d\n",msg2,getpid());
fclose(fp);
return 1;
}
------解决方案--------------------
说的再细一点吧:
fprintf只是写到磁盘缓冲里,fork之后,连带这个磁盘缓冲也一起复制了,而且还不输出,直到fclose(fp)了,才强制刷新磁盘缓冲区,写进磁盘文件。
可以,在fclose(fp)前加个sleep(20);然后在这20秒内看testfile2,不会发现什么也没有,20秒后就一次性全都写进去了。