Assumes UNIX type OS. This ensures that only one instance of the calling application can run at any given time. Using the process id of the current (calling) process it obtains the link to the executable file from the /proc directory by calling stat on /proc/process_id/exe. It then examines all other sub-directories in /proc that are wholly numeric in name (the criteria for identifying current processes) to see if calling stat on subdir/exe results in a link to the same executable. If it does exit is called. If not this function simply returns allowing the calling process to proceed. Arguments: None Returns: None
| Return Type | Function name | Arguments |
|---|---|---|
| void | SingleProc | (void) |
Declared in file: hzProcess.h
Defined in file : hzProcess.cpp
Function Logic:
Function body:
void SingleProc (void)
{
// Category: Process
//
// Assumes UNIX type OS. This ensures that only one instance of the calling application can run at any given time. Using the process id of the
// current (calling) process it obtains the link to the executable file from the /proc directory by calling stat on /proc/process_id/exe. It
// then examines all other sub-directories in /proc that are wholly numeric in name (the criteria for identifying current processes) to see if
// calling stat on subdir/exe results in a link to the same executable. If it does exit is called. If not this function simply returns allowing
// the calling process to proceed.
//
// Arguments: None
// Returns: None
FSTAT fs ; // File status
dirent* pDE ; // Directory entry meta data
DIR* pDir ; // Operating directory
uint32_t ino ; // Inode number of directory entry
uint32_t cpid ; // Current process id
uint32_t xpid ; // Process id derived from sub-dirs of /proc
char buf [512]; // Directory entry name buffer
/*
** ** Obtain current executable
** */
cpid = getpid() ;
sprintf(buf, "/proc/%d/exe", cpid) ;
if (lstat(buf, &fs) == -1)
{
std::cerr << "Could not stat " << buf << std::endl ;
exit(-1);
}
ino = fs.st_ino ;
/*
** ** Open the /proc directory and read it.
** */
pDir = opendir("/proc") ;
if (!pDir)
{
std::cerr << "Cannot examine processes" << std::endl ;
exit(-3);
}
for (; pDE = readdir(pDir) ;)
{
// Eliminate this directory and the parent
if (pDE->d_name[0]== ''.'')
continue ;
// Eliminate all non numeric directories
if (!IsAllDigits(pDE->d_name))
continue ;
xpid = atoi(pDE->d_name) ;
// Ignore self
if (xpid == cpid)
continue ;
sprintf(buf, "/proc/%d/exe", xpid) ;
if (lstat(buf, &fs) == -1)
std::cout << "Could not stat " << buf << std::endl ;
else
{
if (fs.st_ino == ino)
{
std::cout << "pid: " << cpid << " - Have located an existing process of " << xpid << std::endl ;
std::cerr << "Both the existing and current process involve executable with inode of " << ino << std::endl ;
exit(-4);
}
}
}
closedir(pDir) ;
}