How do I implement fork and exec in bash?
Let us suppose script as
echo "Script starts" function_to_fork(){ sleep 5 echo "Hello" } echo "Script ends"
Basically I want that function to be called as new process like in C we use fork and exec calls..
From the script it is expected that the parent script will end and then after 5 seconds, "Hello" is printed.
If the shell process ( bash) calls exec() to run grep, the shell process will be replaced with grep. Grep will work fine but after execution, the control cannot return to the shell because bash process is already replaced. For this reason, bash calls fork(), which does not replace the current process.
A Bash fork bomb is a sequence of Bash commands running a neverending recursive function, resulting in an out of control consumption of system resources eventually making the system become unresponsive or even crash.
On Unix-like operating systems, exec is a builtin command of the Bash shell. It lets you execute a command that completely replaces the current process. The current shell process is destroyed, and entirely replaced by the command you specify.
fork vs execfork starts a new process which is a copy of the one that calls it, while exec replaces the current process image with another (different) one. Both parent and child processes are executed simultaneously in case of fork() while Control never returns to the original program unless there is an exec() error.
Use the ampersand just like you would from the shell.
#!/usr/bin/bash function_to_fork() { ... } function_to_fork & # ... execution continues in parent process ...
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