2017-03-18 50 views
0

我想在下面的C++程序中分離線程,以便即使在進程終止後,線程將繼續向文本文件中寫入一些字符。 問題是我沒有完成它: 當程序終止線程停止寫入「file.txt」文件。你能幫我解決這個問題嗎?或者這是不可能的?不能分離線程永遠C++

#include<thread> 
#include<stdio.h> 
using namespace std; 

void printToFile() 
{ 
    FILE *file; 

    for (int i = 0; true; i++) 
    { 
     fopen_s(&file, "file.txt", "w"); 
     fprintf(file, "%s%d", "n: ",i); 
     fclose(file); 
    } 
    return; 
} 

int main() 
{ 
    thread t(printToFile); 
    t.detach(); 

    return 0; 
} 

回答

0

這是不可能的。當你的「主」線程終止時,它所有的「子線程」也被終止。你想要的是fork()這個寫入文件的獨立進程。

+0

由於fopen_s表明他正在使用VS,他可能需要CreateProcess(),因爲Windows沒有fork()調用。 –

0

不可能。 detach只將線程與其父線程分開,所以父線程不需要擔心清理它。一旦進程死亡,其所有線程也會死亡。