1
votes

I am working on linux.

Is there any way to get the user defined program name, given the PID of that running program?

I want to output the program name, not the process name.

For example: I have a java application, named as stackoverflow.java. Now the process name will be decided by the system which can be different but the program name is stackoverflow.java. So the output should be the program name, given only the PID of that running program.

There are some commands which are fulfilling partial needs like:

cat /proc/"PID"/cmdline -> This will give the command line arguments that creates that process with given "PID". But if we have various programs in different programming languages then the format of the command which runs that program will not be same. So in that case, how to extract the exact program name from this command?

readlink -f /proc/"PID"/exe -> This will give the executable file name related to the process with given "PID". But some processes do not have executable files. In that case, it will not return anything.

1
Your best bet is looking at /proc/PID/cmdline and write if conditions depending on the first or second name. Like if it is python take second. If it is an executable, first one etc.Ajay Brahmakshatriya
Stack Overflow is a site for programming and development questions. This question appears to be off-topic because it is not about programming or development. See What topics can I ask about here in the Help Center. Perhaps Super User or Unix & Linux Stack Exchange would be a better place to ask.jww

1 Answers

0
votes

The ps utility does this. For example,

$ ps 12345
  PID TTY      STAT   TIME COMMAND
12345 pts/1    S      0:00 sleep 20

Here's how to ask for just the command:

$ ps -o command 12345
COMMAND
sleep 20

So you merely need to remove that first line:

$ ps -o command 12345 |awk 'NR>1'
sleep 20

If you want just the command without arguments:

$ ps -o command 12345 |awk 'NR>1 { print $1 }'
sleep

(Note: this won't work for commands with spaces in their names.)