[問題] 如何強迫 printf 寫回資料
一個簡單的測試程式,我將 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
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 3 篇):
Programming 近期熱門文章
PTT數位生活區 即時熱門文章