Search code examples
c++clinuxpid

get process name from process ID in a c/cpp program (I can't use /proc/<pid>/cmdline)


I know this question has been asked a few times, but unfortunately I haven't been able to find an answer that matches my restrictions.

I have a PID (not my process), and I want to find its name. Now, I can't access /proc/<pid>/cmdline (restrictions), and I can't find a way to get the output of ps in my program, besides sending its output to a file and then parsing it (which I need to avoid).

Is there another option?

I am coding in Linux/Android user space in C/C++


Solution

  • It sounds like ps does work (?) but you can't write to a temporary file. (Why? Maybe AppArmor is restricting access to just some processes?)

    If that's true, then you can use a pipe to read the ps output directly into your program, without a temporary file.

    int fds[2];
    pipe(fds);
    
    int pid = fork();
    if (pid == 0) {
      // child
      close(fds[0]);  // close the read end of the pipe in the child
      dup2(1,fds[1]); // move the write end to be stdout
      close(fds[1]);
    
      execlp("ps", "ps", "-p", "blah", NULL);
    } else {
      // parent
      close(fds[1]);  // close the write end of the pipe in the parent.
    
      // read data from fds[0] here
    
      close(fds[0]);
      int status;
      wait(&status); // clean up the zombie ps process
    }
    

    That example leaves out all the error checking (which you must add), and might not be allowed (depending what the nature of your access restrictions might be).