如何像ps -e一样显示过程 [英] how to show proccess like in ps -e

查看:124
本文介绍了如何像ps -e一样显示过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好!

我想做一个简单的C程序,它将像ps -e一样工作.唯一应显示的列是PID和CMD.那就是我的代码:

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

我的问题是:

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

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

2)如何在PID的CID附近写(如果文件夹是数字,我不能用路径粘(?)字符串)?

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

推荐答案

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

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

这篇关于如何像ps -e一样显示过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆