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