I have the following code to cycle through the numeric dirs inside /proc and get the names of the folders by going further into the dir of the given PID:
/proc/PID/cmdline
This is the C code:
char* getNameByPID(const char* cmdline_CmdLinePath, const int PID){
char* chrptr_NameOfProcess;
FILE* fd_CmdLineFile = fopen (cmdline_CmdLinePath, "rt") ; // open the file for reading text if (fd_CmdLineFile) {
if (fd_CmdLineFile) {
chrptr_NameOfProcess = malloc(200);
if (fscanf(fd_CmdLineFile, "%s", chrptr_NameOfProcess) != 1) {
free(chrptr_NameOfProcess);
chrptr_NameOfProcess = NULL;
}
fclose(fd_CmdLineFile);
}
return chrptr_NameOfProcess;
}
void printInfo(int intHasArgs) {
DIR* dir_proc = NULL;
dir_proc = opendir(PROC_DIRECTORY);
if (dir_proc == NULL) {
perror("Couldn't open the " PROC_DIRECTORY " directory");
}
struct dirent* de_DirEntity = NULL;
char smaps_CmdLinePath[100];
char cmdline_CmdLinePath[100];
while ( (de_DirEntity = readdir(dir_proc)) ) {
if ( de_DirEntity->d_type == DT_DIR ) {
if ( isNumeric(de_DirEntity->d_name) ) {
strcpy(smaps_CmdLinePath, PROC_DIRECTORY);
strcpy(cmdline_CmdLinePath, PROC_DIRECTORY);
strcat(smaps_CmdLinePath, de_DirEntity->d_name);
strcat(cmdline_CmdLinePath, de_DirEntity->d_name);
strcat(smaps_CmdLinePath, "/smaps");
strcat(cmdline_CmdLinePath, "/cmdline");
char* procName = getNameByPID(cmdline_CmdLinePath, atoi(de_DirEntity->d_name));
if (procName != NULL && procName[0] != '') {
printf("%sn", procName);
}
}
}
}
closedir(dir_proc) ;
}
It works as expected (printing the names of all the numeric dirs found), but at the end it prints:
free(): invalid size
Aborted (core dumped)
which tells me there’s some memory leakage, but I did add a check and free memory if the initial malloc was unsuccessful:
if (fscanf(fd_CmdLineFile, "%s", chrptr_NameOfProcess) != 1) {
free(chrptr_NameOfProcess);
chrptr_NameOfProcess = NULL;
}
I tried also adding the following:
if (procName != NULL && procName[0] != '') {
printf("%sn", procName);
free(procName);
}
but this didn’t help the issue either.