2011-03-06 75 views
0

我正在做一個負載平衡器(一個非常簡單的)。它會查看用戶閒置了多久,以及系統上的負載以確定進程是否可以運行,並以循環方式處理進程。解析文本文件的簡單方法?

控制過程所需的所有數據都存儲在一個文本文件中。 該文件可能是這樣的:

PID=4390 IDLE=0.000000 BUSY=2.000000 USER=2.000000 
PID=4397 IDLE=3.000000 BUSY=1.500000 USER=4.000000 
PID=4405 IDLE=0.000000 BUSY=2.000000 USER=2.000000 
PID=4412 IDLE=0.000000 BUSY=2.000000 USER=2.000000 
PID=4420 IDLE=3.000000 BUSY=1.500000 USER=4.000000 

這是一所大學的任務,但是解析文本文件不應該是它的一個重要組成部分,這意味着我可以用任何方式是最快的,我執行。

此文件中的條目將隨着流程完成或被添加到控制之下而被添加和刪除。

有關如何解析此問題的任何想法?

謝謝。

+0

解析它很容易。最困難的部分是確保在別的東西寫入時不會嘗試讀取它。 – Blrfl 2011-03-06 14:27:23

+0

我爲此使用羊羣。 – Blackbinary 2011-03-06 14:36:30

回答

1

下面是解析文件的代碼,並說明文件可能不可用(即fopen可能會失敗),或者在讀取它時正在寫入(即fscanf可能會失敗) 。請注意,您可能不想使用的無限循環(這是比您的項目中複製粘貼的實際代碼更多的僞代碼,我沒有嘗試運行它)。還要注意,考慮到那裏的睡眠時間,它可能會很慢:您可能想要使用更高級的方法,這更像是一種黑客攻擊。

int pid; 
float idle, busy, user; 

FILE* fid; 
fpos_t pos; 
int pos_init = 0; 

while (1) 
{ 
    // try to open the file 
    if ((fid = fopen("myfile.txt","rw+")) == NULL) 
    { 
    sleep(1); // sleep for a little while, and try again 
    continue; 
    } 

    // reset position in file (if initialized) 
    if (pos_init) 
    fsetpos (pFile,&pos); 

    // read as many line as you can 
    while (!feof(fid)) 
    { 
    if (fscanf(fid,"PID=%d IDLE=%f BUSY=%f USER=%f",&pid, &idle, &busy, &user)) 
    { 
     // found a line that does match this pattern: try again later, the file might be currently written 
     break; 
    } 

    // add here your code processing data   

    fgetpos (pFile,&pos); // remember current position 
    pos_init = 1; // position has been initialized 
    } 

    fclose(fid); 
} 
+0

您忘記了所有&符號,並且所有字段(減去'pid')都是'float'。 – 2011-03-06 14:34:08

+0

@Matteo:固定,謝謝:P – Greg 2011-03-06 14:36:15

+0

我不確定誰給出正確的答案。我選擇格雷格是因爲你包含循環和文件打開,作爲更完整的答案。 – Blackbinary 2011-03-06 14:46:18

0

在循環中使用fscanf。以下是使用fscanf的GNU C教程。

/* fscanf example */ 
#include <stdio.h> 

typedef struct lbCfgData { 
    int pid; 
    double idle; 
    double busy; 
    double user; 
} lbCfgData_t ; 

int main() 
{ 
    // PID=4390 IDLE=0.000000 BUSY=2.000000 USER=2.000000 
    lbCfgData_t cfgData[128]; 

    FILE *f; 

    f = fopen ("myfile.txt","rw+"); 
    for ( int i = 0; 
      i != 128 // Make sure we don't overflow the array 
      && fscanf(f, "PID=%u IDLE=%f BUSY=%f USER=%f", &cfgData[i].pid, 
       &cfgData[i].idle, &cfgData[i].busy, cfgData[i].user) != EOF; 
      i++ 
     ); 

    fclose (f); 
    return 0; 
} 
1

至於剛纔分析而言,這樣的事情在一個循環:

int pid; 
float idle, busy, user; 
if(fscanf(inputStream, "PID=%d IDLE=%f BUSY=%f USER=%f", %pid, &idle, &busy, &user)!=4) 
{ 
    /* handle the error */ 
} 

但作爲@Blrfl指出,最大的問題是避免mixups當你的應用程序讀取文件其他人正在寫信給它。要解決這個問題,你應該使用鎖或類似的東西;見例如系統調用flock

+0

是的,我正在使用羊羣 – Blackbinary 2011-03-06 14:45:43