how to show proccess like in ps -e

坚强是说给别人听的谎言 提交于 2019-12-01 14:27:58

问题


Hello!

I wanto to make simple c proggram what will work like ps -e. The only colums that should be shown are PID and CMD. Thats my code:

#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; 
}

My questins are:

1) How i can show only folders with numbers(i don't know how to implement regcomp())?

2)How to near PID write CMD (I can't glue(?) strings with path if is folder with number)?


回答1:


This is an hint ... Try to develop your code starting from this! :)

#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;
}


来源:https://stackoverflow.com/questions/47439782/how-to-show-proccess-like-in-ps-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!