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++
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).
If you use Android, and you do not have root permission, you can try with this function:
public static String getAppName(Context ctx, int PID){
ActivityManager mng
= (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
for(RunningAppProcessInfo processInfo : mng.getRunningAppProcesses()){
if(processInfo.pid == PID){
return processInfo.processName;
}
}
return "not found PID";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.