Code:
/*This program will scan through a directory
if it finds subdirectories within it, it will
check if the name of the directory is a digit
if it is it will return 1, otherwise a 0. Based
upon the return value, the program will print the
filename which was matched i.e. 1 was returned. */
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
#include <dirent.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <regex.h>
#include <unistd.h>
/*prototypes*/
int matchDetails(char* filename,char* path);
void printDetails(char* filename,char* path);
char *get_regerror(int errcode,regex_t *compiled);
int main(void){
int result,count,index; /*Set Conditions*/
char path[] = "/proc"; /*Path to the proc directory*/
struct dirent **direntp; /*Directory entry pointer*/
struct stat sbuf; /*Holds information about files*/
if (stat(path,&sbuf) != -1){
if(S_ISDIR(sbuf.st_mode)){
count = scandir(path,&direntp,NULL,alphasort);
if(count){
char temp[FILENAME_MAX];
printf("PID\tTTY\t\tTIME\tCMD\n");
for(index=0; index<count; ++index){
strcpy(temp,path);
result = matchDetails(direntp[index]->d_name,temp);
if(result > 0) /*If directory name was matched*/
printDetails(direntp[index]->d_name,temp);
free(direntp[index]);
}
}else{
fprintf(stderr,"Can't open %s\n",path);
exit(EXIT_FAILURE);
}
}else
return;
}else{
fprintf(stderr,"Can't stat %s\n",path);
return;
}
return EXIT_SUCCESS;
}
/*Used to find process directories*/
int matchDetails(char* filename,char* path){
int status,regstat;
char *pattern = "[0-9]+"; /*Match digits only*/
char *result;
struct stat sbuf;
/*Get the full pathname*/
strcat(path,"/");
strcat(path,filename);
/*Stat the full path name*/
if(stat(path,&sbuf) != -1){
if(S_ISDIR(sbuf.st_mode)){ /*If a directory*/
regex_t re;
if((regstat = regcomp(&re,pattern,REG_EXTENDED | REG_NOSUB)) != 0){
result = get_regerror(regstat,&re);
fprintf(stderr,"%s\n",result);
return(0);
}
if((status = regexec(&re,filename,(size_t) 0,NULL,0)) != 0)
return(0);
regfree(&re);
}else
return(0);
}else{
fprintf(stderr,"Can't stat %s\n",filename);
return(0);
}
return(1);
}
/*Print the process information*/
void printDetails(char* filename,char* path){
FILE *f_name;
int pid;
/*Format the path*/
strcat(path,"/");
strcat(path,filename);
strcat(path,"/");
strcat(path,"stat");
if((f_name = fopen(path,"r")) != NULL){
fscanf(f_name,"%d",pid);
printf("%d\n",pid);
fclose(f_name);
}else
fprintf(stderr,"Can't open %s\n",path);
}
/*Used to store regex errors*/
char *get_regerror(int errcode,regex_t *compiled){
size_t length = regerror(errcode,compiled,NULL,0);
char *buffer = malloc(length);
(void) regerror(errcode,compiled,buffer,length);
return buffer;
}