while reading about linux I got :
By default, variables created within a script are only available to the current shell; child processes (sub-shells) will not have access to values that have been set or modified. Allowing child processes to see the values, requires use of the export command.
I tried to find about subshells then I came across Are there any command to see how processes are working?, and I found ltrace could be used for that, when I searched for how to use ltrace
or strace
, I found that PID
is required attribute for that.
now, If I want to know the PID for $ cp file1 file2
,how would I do that??
so that I can use ltrace
to it??
PID of current command
The PID of a command in your own shell is shown when you start the command in background. If the current command runs in the foreground, the shell mostly waits for it to finish, we have to wait too - except we want to use a tool outside this shell; See below for that option.
As an example command, I'll use this
ping
that sends a request every 5 seconds for 10 times:Now, I'll use
&
to run it in the background:The
[1] 12238
tells us that the process has the process id, short PID 12238; And that it's the first background job currently running in this shell.Example: tracing library calls
In the same terminal we get the output of
ping
, so we better run ltrace in another one (ping
has special root permissions, so we needsudo
to mess with its inside):That's a trace of the library calls during two 'pings'.
Finding PIDs of running processes in general
As the title question is not very specific, here are some other ways to find PIDs of currently running commands:
Search for processes by command name
pgrep -x cmd
Note that the variantpgrep cmd
is wrong: it mathes as substringSearch by command line with arguments
pgrep -f cmdarg
List processes that belong to the current shell (session), like background processes, or the shell itself
ps -s $$
List all processes: "process status"
ps aux
Listing processes in a more interactive way: "table of processes"
top
And all you need at once: a table of processes, integrated with
ltrace
andstrace
:htop
It's a variant of
top
with enhanced UI and configurability, plus some extras:Choose a process with the cursor line, and press L for
ltrace
, or s forstrace
!bash
,dash
(and many other shells) have built-in commands for job control. If you run a command in the backgroundyou can discover all the background commands of the current shell:
If you need the process ID of one of them, you can get it with
jobs -p %N
, whereN
is the job ID in the job list (first column) above. There's also a special variable$!
that the shell will substitute with the PID of the command executed in the background most recently.For details and more options, have a look at the relevant section of the manuals of
bash(1)
(direct link to job control section in HTML version),dash(1)
or your shell of choice. TLDP has a great section on job control as well.