我想在Linux上用C構建一個進程記錄器,但是沒有正確的解決它。我希望它有3個列:USER,PID,COMMAND。我正在使用ps aux
的輸出並試圖將其動態追加到數組中。也就是說,對於每行ps aux
輸出,我想添加一行到我的數組。爲什麼我的動態2D字符數組中的值被覆蓋?
這是我的代碼。 (爲了保持輸出短路,我只用grep的昇華。但是,這可能是任何東西。)
#define _BSD_SOURCE
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char** processes = NULL;
char* substr = NULL;
int n_spaces = 0;
int columns = 1;
char line[1024];
FILE *p;
p = popen("ps -eo user,pid,command --sort %cpu | grep sublime", "r");
if(!p)
{
fprintf(stderr, "Error");
exit(1);
}
while(fgets(line, sizeof(line) - 1, p))
{
puts(line);
substr = strtok(line, " ");
while(substr != NULL)
{
processes = realloc(processes, sizeof(char*) * ++n_spaces);
if(processes == NULL)
exit(-1);
processes[n_spaces - 1] = substr;
// first column user, second PID, third all the rest
if(columns < 2)//if user and PID are already in array, don't split anymore
{
substr = strtok(NULL, " ");
columns++;
}
else
{
substr = strtok(NULL, "");
}
}
columns = 1;
}
pclose(p);
for(int i = 0; i < (n_spaces); i++)
printf("processes[%d] = %s\n", i, processes[i]);
free(processes);
return 0;
}
的for循環結尾處的輸出看起來是這樣的。
processes[0] = user
processes[1] = 7194
processes[2] = /opt/sublime_text/plugin_host 27184
processes[3] = user
processes[4] = 7194
processes[5] = /opt/sublime_text/plugin_host 27184
processes[6] = user
processes[7] = 27194
processes[8] = /opt/sublime_text/plugin_host 27184
processes[9] = user
processes[10] = 27194
processes[11] = /opt/sublime_text/plugin_host 27184
但是,從puts(line)
我得到的數組實際上應該包含這樣的:
user 5016 sh -c ps -eo user,pid,command --sort %cpu | grep sublime
user 5018 grep sublime
user 27184 /opt/sublime_text/sublime_text
user 27194 /opt/sublime_text/plugin_host 27184
因此,顯然所有的值都被覆蓋,我想不通爲什麼...(另外,我沒有得到processes[0] = 7194
和processes[4] = 7194
的值7194
來自哪裏)。
我在這裏做錯了什麼?是否有可能使輸出看起來像puts(line)
的輸出?
任何幫助,將不勝感激!
這裏沒有二維數組。你有一個一維數組的指針。對於每個指針,分配一塊內存並將讀取的子字符串複製到那裏。 – Lundin