下面是我的代碼,將由每個線程調用以將ping命令的輸出寫入文本文件。該文件已正確創建,但沒有任何內容。現在我沒有創建任何線程,只是這樣調用該函數從主:將ping命令的輸出寫入c中的文本文件的問題?
customPing("www.google.com", 10, 2, 1);
void customPing(char *url, int test_interval,int samplesPerTest, int testDuration)
{
printf("-->%s %d(sec) %d %d(hrs)\n", url, test_interval, samplesPerTest, testDuration);
int durationInProgress = 0,
durationInSeconds = testDuration * 10,
n = samplesPerTest;
char pingCmd[80];
char filename[10];
FILE *fptr;
sprintf(filename, "pingResult%d.txt", fileCounter++);
fptr = fopen(filename, "a");
sprintf(pingCmd, "ping -n %d %s >> %s ", n, url,filename);
printf("ping command: %s\n", pingCmd);
while (durationInProgress <= durationInSeconds)
{
system(pingCmd);
durationInProgress += test_interval;
printf("Going to sleep...\n");
fclose(fptr);
Sleep(test_interval);
fptr = fopen(filename, "a");
}
printf("***Done***\n");
}
OUTPUT:
1. Enter url: www.google.ca
2. Enter Testing-Interval(10 sec, 20 sec, etc): 10
3. Test Samples per test (10, 100 etc): 2
4. Start test (yes/no): yes
4. Test Duration (1 hr, 24 hrs, etc) 1
***Test Starting***
-->www.google.com 10(sec) 2 1(hrs)
ping command: ping -n 2 www.google.com >> pingResult0.txt
The process cannot access the file because it is being used by another process.
Going to sleep...
The process cannot access the file because it is being used by another process.
Going to sleep...
***Done***
Press any key to continue . . .
什麼我做錯了任何想法? ? 我使用Visual Studio 2008,Win Vista。(如果有幫助) 謝謝。
而是平的輸出定向到一個文件,然後讀取文件的,爲什麼不直接使用'popen'管道結果從平直接回父? – 2011-03-30 23:42:03