While there is many different ways to do it, having a dedicated tool to count how many processes an executable file are currently running was one of my need. And because I wanted a really performant way of doing it, I wrote this tiny tool named pcount.
Here is the full C source code, no specific license attached, the code is really too trivial to claim for anything ^^:
/* pcount.c - A (simple but fast) process counter
* returns the number of Linux process matching the given executable filename
* 20121126 - dlb < dlb at atdan dot net >
* The goal here is pure performance, no other checks than the bare necessary
* are made, feel free to do a bloated version if you want ^^
*
* compile: gcc -Wall -o pcount pcount.c
*/
#include <dirent.h>
#include <stdio.h>
#include <string.h> // for strcmp()
#include <unistd.h> // for chdir() and readlink()
#define PROC_DIR "/proc"
int main (int argc, char *argv[]) {
DIR *dir; // our dir handler
struct dirent *entry; // current directory entry
char lnk_path[256]; // symlink pathname
char tgt_path[256]; // target pathname
int len, pcount = 0; // guess what...
/* get the executable pathname to check for as an argument */
if (argc < 2) {
fprintf (stderr, "usage: %s \n", argv[0]);
return (1);
}
/* go into the PROC_DIR directory */
if (chdir(PROC_DIR) != 0) {
perror ("Can't change directory to "PROC_DIR);
return (2);
}
/* open the PROC_DIR directory */
dir = opendir (PROC_DIR);
if (dir == NULL) {
perror ("Can't open directory "PROC_DIR);
return (3);
}
/* read all entries */
while ((entry = readdir(dir)) != NULL) {
/* check for a PROC_DIR//exe symlink */
len = sprintf (lnk_path, "%s/%s/%s",
PROC_DIR, entry->d_name, "exe");
len = readlink (lnk_path, tgt_path, sizeof(tgt_path));
if (len != -1) { /* yep, found one */
tgt_path[len] = '\0'; /* readlink does not add it */
if (!strcmp(tgt_path, argv[1]))
pcount++;
}
}
/* end with no error */
closedir (dir);
printf ("%d\n", pcount);
return (0);
}