Objective: Get the command line arguments passed to a process on Linux using proc
.
The Linux /proc
filesystem can be used to get the arguments passed to a process. First, we need to get the process id or PID (process id) of the process that we are interested in. Then we will need to examine the contents of the following file.
1 |
/proc/PID/cmdline |
So, let’s say that we want to get the arguments passed to the dhclient
(DHCP client) process. First, we get the PID of the process.
1 2 |
$ ps -e | grep dhclient 2030 ? 00:00:00 dhclient |
The PID of the process is 2030. Now we can examine the cmdline
file for that process. The arguments in the cmdline
file are NUL-separated, so will need to perform some conversion. Use one of the commands below to read the contents of the cmdline
file for the dhclient
process.
1 2 |
$ cat /proc/2030/cmdline | xargs -0 dhclient -v -pf /run/dhclient.eth0.pid -lf /var/lib/dhcp/dhclient.eth0.leases eth0 |
1 2 |
$ cat /proc/2030/cmdline | tr '\0' ' ' dhclient -v -pf /run/dhclient.eth0.pid -lf /var/lib/dhcp/dhclient.eth0.leases eth0 |
1 2 3 4 5 6 7 8 |
$ strings -n 1 /proc/2030/cmdline dhclient -v -pf /run/dhclient.eth0.pid -lf /var/lib/dhcp/dhclient.eth0.leases eth0 |
If you using the strings command to read the cmdline file, make sure the “-n 1” argument is passed, else some of the arguments will not be printed.
If you have pgrep
, which is part of the procps
package, then you can also use the following syntax to retrieve the arguments.
1 2 |
$ pgrep -lf dhclient 2030 dhclient -v -pf /run/dhclient.eth0.pid -lf /var/lib/dhcp/dhclient.eth0.leases eth0 |
Notice that pgrep
also prints out the process id and process name together with the command line arguments.