问题描述
所以,我知道如果我们想查看所有正在运行的进程,我们可以在 shell 中编写“ps -aux”,但我正在开发这个程序,该程序在某些时候必须打印当时所有正在运行的进程。任何想法如何编码?
解决方法
您可以从 C 代码中执行 shell 命令并读取此命令的输出,如 https://www.cs.uleth.ca/~holzmann/C/system/shell_commands.html
中所述在 C 中,如果 shell 命令不需要输出,则使用 system()
,但是当您需要输出时,使用 popen()
,示例在 https://rosettacode.org/wiki/Get_system_command_output#C 中
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char **argv)
{
if (argc < 2) return 1;
FILE *fd;
fd = popen(argv[1],"r");
if (!fd) return 1;
char buffer[256];
size_t chread;
/* String to store entire command contents in */
size_t comalloc = 256;
size_t comlen = 0;
char *comout = malloc(comalloc);
/* Use fread so binary data is dealt with correctly */
while ((chread = fread(buffer,1,sizeof(buffer),fd)) != 0) {
if (comlen + chread >= comalloc) {
comalloc *= 2;
comout = realloc(comout,comalloc);
}
memmove(comout + comlen,buffer,chread);
comlen += chread;
}
/* We can now work with the output as we please. Just print
* out to confirm output is as expected */
fwrite(comout,comlen,stdout);
free(comout);
pclose(fd);
return 0;
}
另一个例子是在 https://www.lix.polytechnique.fr/~liberti/public/computing/prog/c/C/FUNCTIONS/popen.html
您还可以使用 ps -aux
(进程表)代替 top
(进程状态)