/*********************************************************************************
*  _   _                _______           _                                _     *
* | \ | |              | |  _  \         (_)                              | |    *
* |  \| | _____   _____| | | | |_____   ___  ___ ___  ___   ___ ___  _   _| | __ *
* | . ` |/ _ \ \ / / _ \ | | | / _ \ \ / / |/ __/ _ \/ __| / __/ _ \| | | | |/ / *
* | |\  | (_) \ V /  __/ | |/ /  __/\ V /| | (_|  __/\__ \| (_| (_) | |_| |   <  *
* \_| \_/\___/ \_/ \___|_|___/ \___| \_/ |_|\___\___||___(_)___\___(_)__,_|_|\_\ *
*                                                                                *
**********************************************************************************
* gofc.c        JST Lawrence   March 2023       get count of open files for a    *
*                                               process.                         *
*                                                                                *
* 21-Mar-2023 V1.0 JSTL Created.                                                 *
*                                                                                *
*********************************************************************************/
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <dirent.h>

/*********************************************************************************
*                                                                                *
* Function declarations                                                          *
*                                                                                *
*********************************************************************************/
int GetOpenFileCount(pid_t Requested);

/*********************************************************************************
*                                                                                *
* GetOpenFileCount() - returns number of open files or -1 on error               *
*                                                                                *
*********************************************************************************/
int GetOpenFileCount(pid_t Requested)
{
    struct     dirent *dir;
    DIR       *Directory;
    pid_t      getpid(void);
    char       Path[256];
    int        FileCount=0;

// If no PID requested, then get own
    if(0==Requested)Requested=getpid();

// Compose path string
    sprintf(Path,"/proc/%d/fd",Requested);

// Open directory and check for success
    Directory=opendir(Path);
    if(Directory==NULL)return (-1);

// Read directory until end
    while((dir=readdir(Directory))!=NULL)
    {
        FileCount++;
    }

// Finished reading the directory so close
    closedir(Directory);

// Adjust for . and ..
    FileCount=FileCount-2;

    return FileCount;
}