C-如何显示PS -E中的Proccess



你好!

我希望使简单的c proggram像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      CMDn");
while ((entry = readdir(dir)) != NULL)
printf("  %sn", 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;
}

最新更新