如何在 ps -e 中显示过程 [英] how to show proccess like in ps -e

查看:19
本文介绍了如何在 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
");
while ((entry = readdir(dir)) != NULL)
printf("  %s
", 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 附近写入 CMD(如果是带有数字的文件夹,我不能用路径粘合(?)字符串)?

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天全站免登陆