【问题标题】:How to see all running processes with a C program?如何使用 C 程序查看所有正在运行的进程?
【发布时间】:2021-06-10 01:22:52
【问题描述】:

所以,我知道如果我们想查看所有正在运行的进程,我们可以在 shell 中编写“ps -aux”,但我正在开发这个程序,在某些时候必须打印所有正在运行的进程。任何想法如何编码?

【问题讨论】:

  • 您好,欢迎来到 Stackoverflow。你问的问题非常广泛。您可能想了解如何在 stackoverflow 上提出与编程相关的详细问题。
  • 一个简单的解决方案是读取/proc中的所有文件
  • 这在一定程度上取决于您所指的 Unix,但很有可能它的 ps 的源是开放的。看看它。但是这里的问题必须是关于一个具体的问题,你的问题太宽泛了。获取tour 并查看How to Askhelp center
  • 查看pstophtop 或您喜欢的任何代码库的源代码。

标签: c linux unix process


【解决方案1】:

您可以在 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, 1, 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(进程表)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 2012-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多