如何像 ps -e 那样显示进程

how to show proccess like in ps -e

您好!

我想制作简单的 c 程序,其工作方式类似于 ps -e。应该显示的唯一列是 PID 和 CMD。那是我的代码:

#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
#include <stdio.h>
#include <regex.h>
int main()
{
DIR *dir;
struct dirent *entry;
if ((dir = opendir("/proc")) == NULL)
perror("operation error");
else 
{
printf("PID      CMD\n");
while ((entry = readdir(dir)) != NULL)
printf("  %s\n", entry->d_name);
closedir(dir);
}
return 0; 
}

我的问题是:

1) 如何只显示带数字的文件夹(我不知道如何实现 regcomp())?

2) 如何在 PID 附近写入 CMD(如果是带编号的文件夹,我不能将字符串与路径粘贴(?))?

这是一个提示...尝试从这里开始开发您的代码! :)

#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>

int readData(char *dirname);

int readData(char *dirname)
{
    FILE * file;
    char buffer[1024]={0};

    sprintf(buffer,"/proc/%s/stat",dirname);

    file = fopen(buffer,"r");
    if (!file)
        return errno;

    while(fgets(buffer,sizeof(buffer),file))
        puts(buffer);

    if (file)
        fclose(file);

    return errno;
}

int main(void)
{
    DIR * dir;

    struct dirent * entry;

    if ( (dir = opendir("/proc")) == NULL )
        perror("operation error");

    while ((entry = readdir(dir))) {
        if ( strlen(entry->d_name) == strspn(entry->d_name, "0123456789"))
            if (readData(entry->d_name))
                break;
    }

    if (dir)
        closedir(dir);

    return errno;
}