微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 C 程序查看所有正在运行的进程?

如何解决如何使用 C 程序查看所有正在运行的进程?

所以,我知道如果我们想查看所有正在运行的进程,我们可以在 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(进程状态)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。