Reputation: 35
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.
Upvotes: 3
Views: 2275
Reputation: 16246
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.)
Upvotes: 1