作者N2I (NII)
看板Programming
标题[问题] 如何强迫 printf 写回资料
时间Fri Mar 2 10:10:23 2007
一个简单的测试程式,我将 stdout 转向到档案 log,程式执行後,会停在
loop 里,按下 ctrl+z 或 ctrl+c 强迫程式结束。
检查 log 档, ls 的结果都正确写入,可是字串HELLO却没有正确写入,我已经呼叫
fsync() 强迫将 buffer 资料写回了,为甚麽还是没有?
是不是有甚麽地方我没有注意到呢,谢谢罗
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
int main(void) {
int fd;
FILE *fp = NULL;
if ( (fp=fopen("log", "w")) == NULL ) {
printf("fopen error");
exit(1);
}
fd = fileno(fp);
if ( dup2(fd, STDOUT_FILENO) == -1 ) {
fprintf(stderr, "Redirect Standard Out error");
exit(1);
}
printf("HELLO\n");
fsync(fd);
system("ls");
while(1);
return 0;
}
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 59.124.92.123