Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get PID from forked child process in shell script

Tags:

linux

shell

pid

I believe I can fork 10 child processes from a parent process.

Below is my code:

#/bin/sh fpfunction(){     n=1     while (($n<20))     do         echo "Hello World-- $n times"         sleep 2         echo "Hello World2-- $n times"         n=$(( n+1 ))     done }  fork(){     count=0     while (($count<=10))     do         fpfunction &         count=$(( count+1 ))     done }  fork 

However, how can I get the pid from each child process I just created?

like image 784
Sam Avatar asked Jun 28 '13 03:06

Sam


People also ask

Does fork return child PID?

System call fork() returns the child process ID to the parent and returns 0 to the child process.

How do I find my child process ID?

We can find the PIDs of the child processes of a parent process in the children files located in the /proc/[pid]/task/[tid] directories.

How do I find the subprocess PID in Linux?

There is a solution that can get the PID of sub_process1: Enumerate all processes with the command ps aux ; Get PPID(parent process ID) for each process with the command ps -f [PID] . If the PPID is equal to the PID of process1, the process must be sub_process1.

What is the PID after fork?

Upon successful completion, fork() returns a value of 0 to the child process and returns the process ID of the child process to the parent process. Otherwise, a value of -1 is returned to the parent process, no child process is created, and the global variable errno is set to indi- cate the error.


Video Answer


2 Answers

The PID of a backgrounded child process is stored in $!.

fpfunction & child_pid=$! parent_pid=$$ 

For the reverse, use $PPID to get the parent process's PID from the child.

fpfunction() {     local child_pid=$$     local parent_pid=$PPID     ... } 

Also for what it's worth, you can combine the looping statements into a single C-like for loop:

for ((n = 1; n < 20; ++n)); do do     echo "Hello World-- $n times"     sleep 2     echo "Hello World2-- $n times" done 
like image 91
John Kugelman Avatar answered Oct 16 '22 11:10

John Kugelman


From the Bash manual:

!

Expands to the process ID of the most recently executed background (asynchronous) command.

i.e., use $!.

like image 30
Oliver Charlesworth Avatar answered Oct 16 '22 10:10

Oliver Charlesworth