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?
System call fork() returns the child process ID to the parent and returns 0 to the child process.
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.
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.
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.
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
From the Bash manual:
!
Expands to the process ID of the most recently executed background (asynchronous) command.
i.e., use $!
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With