[linux c/c++] 通过读取 /proc 路径获取指定进程名的信息

发布时间:2024年01月02日
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>


static bool checkServiceRunning(const char *servicename){
  constexpr int BUF_SIZE = 4096;
  bool ret = false;
  DIR *dir;
  struct dirent *ptr;
  FILE *fp;
  char filePath[512] = {0};
  char buf[BUF_SIZE] = {0};
  char key[128] = {0};
  char value[512] = {0};

  dir = opendir("/proc");
  if(dir!=NULL){
    while((ptr = readdir(dir)) != NULL){
      if(strcmp(ptr->d_name, ".") == 0 || (strcmp(ptr->d_name, "..") == 0))
        continue;
      if(ptr->d_type != DT_DIR)
        continue;

      sprintf(filePath, "/proc/%s/status", ptr->d_name);
      fp = fopen(filePath, "r");
      if(fp != NULL){
        memset(buf,0,sizeof(buf));
        if(fgets(buf,BUF_SIZE-1,fp)==NULL){
          fclose(fp);
          continue;
        }

        memset(key,0,sizeof(key));
        memset(value,0,sizeof(value));
        if(EOF == sscanf(buf, "%s %s", key, value)){
          fclose(fp);
          continue;
        }

        if (strstr(key,"Name") && !strcmp(servicename, value)){
          rewind(fp);
          while(fgets(buf,BUF_SIZE-1,fp) != NULL){
            printf("[%s] %s",ptr->d_name,buf);
          }
          ret = true;
          break;
        }
        fclose(fp);
      }
    }
    closedir(dir);
  }
  return ret;
}

int main()
{
   checkServiceRunning("sftp-server");
}
文章来源:https://blog.csdn.net/ykun089/article/details/135341152
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。