Search code examples
c++cc++11freebsd

How to get the process name of a PID in FreeBSD?


I am trying to write a function which returns the parent process name,
if it is bash, then it should return bash.

const std::string &getParentProcessName() {
  static std::string name;
  auto ppid = getppid();
#ifdef __FreeBSD__
  // ?????
#else
 ...
#endif
  name = "unknown";
  return name;
}

Solution

  • Use the kinfo_getproc function

       pid_t pid = ...;
       struct kinfo_proc *proc = kinfo_getproc(pid);
       if (proc) {
         printf("Name %s\n", proc->ki_comm); 
         //ki_comm should be the program name
         //see the sys/user.h header file for other relevant fields.
    
         free(proc);
       }
    

    See also the libprocstat functions for aquiring process information.