[問題] 兩個process寫入同一個檔案的疑問

看板C_and_CPP (C/C++)作者 (掰掰惹 仙度瑞拉)時間1年前 (2022/07/09 21:16), 編輯推噓4(407)
留言11則, 5人參與, 1年前最新討論串1/2 (看更多)
開發平台(Platform): (Ex: Win10, Linux, ...) Linux kali 5.18.0-kali2-amd64 #1 SMP PREEMPT_DYNAMIC Debian 5.18.5-1kali1 (2022-06-20) x86_64 GNU/Linux 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) gcc (Debian 11.3.0-3) 11.3.0 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 我有兩個process開啟同一個file,且兩個process同時向file寫入字串 一個寫入"a",一個寫入"b",各自重複寫入200次 每一次寫入,兩個process就會printf出當前ftell的值 問題: 我期待看到file中ab會交替出現 但並沒有,而是a全部出現完才換b,或者b出現完才換a 不過從console上印出的ftell值卻又顯示 這兩個process顯然是交替執行著,並不是一個執行完才換另一個 既然如此,為什麼file的內容不是交替的顯示a和b呢 請問要如何做才能看到ab交替的結果 謝謝 餵入的資料(Input): 預期的正確結果(Expected Output): file中a和b交替顯示 錯誤結果(Wrong Output): 200個a全部顯示完才換b,或者200個b顯示完才換a 程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔) #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { FILE *pfile; int id = fork(); if (id == 0) { char *str = "a"; pfile = fopen("testfile", "a"); if (pfile) { int i; for (i = 0; i < 200; i++) { printf("a = %d\n", ftell(pfile)); fwrite(str, 1, strlen(str), pfile); } } } else if (id > 0) { printf("id = %d\n", id); char *str = "b"; pfile = fopen("testfile", "a"); if (pfile) { int i; for (i=0;i<200;i++) { printf("b = %d\n", ftell(pfile)); fwrite(str, 1, strlen(str), pfile); } } } fclose(pfile); return 0; } 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 125.229.74.160 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1657372608.A.F32.html

07/09 21:30, 1年前 , 1F
fopen 這一系列的 function 會做 buffering
07/09 21:30, 1F

07/09 21:30, 1年前 , 2F
如果你需要 atomic write 可以直接用 write system call
07/09 21:30, 2F

07/09 21:32, 1年前 , 3F
或你可以在一開始用 setvbuf(pfile, NULL, _IOFBF, 0);
07/09 21:32, 3F

07/09 21:33, 1年前 , 4F
關閉這個 pfile 的 buffering
07/09 21:33, 4F

07/09 21:52, 1年前 , 5F
謝謝 我用write就可以了
07/09 21:52, 5F

07/10 00:44, 1年前 , 6F
即使write atomic也不能保證ab交替,還是有可能出現連續一
07/10 00:44, 6F

07/10 00:44, 1年前 , 7F
些a然後連續一些b,因為process A只知道一直寫a,不知道b
07/10 00:44, 7F

07/10 00:44, 1年前 , 8F
寫入了沒,反之亦然,除非process A寫入a後通知process B
07/10 00:44, 8F

07/10 00:44, 1年前 , 9F
然後等待通知,B寫入b後通知A並等待,不斷交替
07/10 00:44, 9F

07/10 21:20, 1年前 , 10F
你真的要交替寫入的話需要IPC才有辦法 IPC cond_var也可
07/10 21:20, 10F

07/11 09:36, 1年前 , 11F
不然你再寫一個thread專門接收其他thread寫檔?
07/11 09:36, 11F
文章代碼(AID): #1YoN_0yo (C_and_CPP)
文章代碼(AID): #1YoN_0yo (C_and_CPP)