title: Linux - Get window title from pid
body: <p>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:</p>
  <pre><code>#include &lt;iostream&gt;
  #include &lt;glob.h&gt;
  #include &lt;cstdio&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  #include &lt;sys/types.h&gt;
  
  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(&quot;/proc/*/comm&quot;, 0, NULL, &amp;pglob) != 0)
          return pid;
  
      /* The comm files include trailing newlines, so... */
      procname = static_cast&lt;char*&gt;(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&lt;char*&gt;(malloc(buflen));
  
      for (i = 0; i &lt; pglob.gl_pathc; ++i) {
          FILE *comm;
          char *ret;
  
          /* Read the contents of the file. */
          if ((comm = fopen(pglob.gl_pathv[i], &quot;r&quot;)) == 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(&quot;/proc/&quot;));
              break;
          }
      }
  
      /* Clean up. */
      free(procname);
      free(readbuf);
      globfree(&amp;pglob);
  
      return pid;
  }
  
  int main(int argc, char const *argv[])
  {
      cout &lt;&lt; find_pid(&quot;brave&quot;) &lt;&lt; endl;
  
      return 0;
  }
  </code></pre>
  <p>I copied and modified code from this post - <a href="https://stackoverflow.com/questions/5232763/linux-get-pid-of-process">linux - get pid of process</a>. Please help me.</p>