如何在ps -e中显示proccess

你好!

我想制作简单的c程序,它会像ps -e一样工作。 应该显示的唯一列是PID和CMD。 那是我的代码:

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