I am making an app blocker with c++ and I need it to block urls. To block urls it will get the window name of the current tab that it is focused on. Here is the code I've got so far:
#include <iostream>
#include <glob.h>
#include <cstdio>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
using namespace std;
pid_t find_pid(const char *process_name)
{
pid_t pid = -1;
glob_t pglob;
char *procname, *readbuf;
int buflen = strlen(process_name) + 2;
unsigned i;
/* Get a list of all comm files. man 5 proc */
if (glob("/proc/*/comm", 0, NULL, &pglob) != 0)
return pid;
/* The comm files include trailing newlines, so... */
procname = static_cast<char*>(malloc(buflen));
strcpy(procname, process_name);
procname[buflen - 2] = '\n';
procname[buflen - 1] = 0;
/* readbuff will hold the contents of the comm files. */
readbuf = static_cast<char*>(malloc(buflen));
for (i = 0; i < pglob.gl_pathc; ++i) {
FILE *comm;
char *ret;
/* Read the contents of the file. */
if ((comm = fopen(pglob.gl_pathv[i], "r")) == NULL)
continue;
ret = fgets(readbuf, buflen, comm);
fclose(comm);
if (ret == NULL)
continue;
/*
If comm matches our process name, extract the process ID from the
path, convert it to a pid_t, and return it.
*/
if (strcmp(readbuf, procname) == 0) {
pid = (pid_t)atoi(pglob.gl_pathv[i] + strlen("/proc/"));
break;
}
}
/* Clean up. */
free(procname);
free(readbuf);
globfree(&pglob);
return pid;
}
int main(int argc, char const *argv[])
{
cout << find_pid("brave") << endl;
return 0;
}
I copied and modified code from this post - linux - get pid of process. Please help me.