note that the /proc/ directory holds a directory for each running process' PID
for example /proc/1 is PID 1
under that directory there's the cmdline file which can be used to determine the PID's command, i.e:
cat /proc/1/cmdline
/usr/lib/systemd/systemd
you can traverse the /proc/[09]* irectories looking for a cmdline that matches what you are looking for, when you match that command you can simply check if the cmdline still matches the original one(the same PID can be used for another process if it had terminated
here's a simple piece of code that gets that job done:
I haven't written most of the error correction(program crashes if the application isn't found, some other errors that cause segfault)
#include
#include
#include
int main(int argc, char* argv[]) {
if (argc != 2){
printf("usage:\nproc <processname>\n");
return 2;
}
char * processName = argv[1];
int pid = 0;
FILE *processFile;
char *monitoredProcess;
DIR *root;
struct dirent *dir;
root = opendir("/proc/");
if (root)
{
int reading = 0;
while((dir=readdir(root))!=NULL && reading==0)
{
// printf("dir name:%i\n",dir->d_ino);
if (dir->d_name[0] > 47 && dir->d_name[0] < 58) {
char directory[128];
strcpy(directory,"/proc/");
strcat(directory,dir->d_name);
strcat(directory,"/cmdline");
processFile = fopen(directory,"r");
if (processFile == NULL) {
printf("Error");
return 1;
}
char line[2048];
while (fgets(line, sizeof line, processFile) != NULL) {
if(strstr(line,processName)) {
printf("%s\n",directory);
monitoredProcess = directory;
reading = 1;
}
//the pid has been determined at this point, now to monitor
}
}
}
//monitoring
printf("monitoring %s\n",monitoredProcess);
while(processFile=fopen(monitoredProcess,"r")) {
char line[2048];
while (fgets(line, sizeof line, processFile) != NULL) {
if(strstr(line,processName) == NULL)
printf("application terminated\n");
}
sleep(3);
fclose(processFile);
}
} else
printf("unable to open folder\n");
}