Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fork and exec in bash

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.

like image 793
Abhijeet Rastogi Avatar asked Jun 22 '10 19:06

Abhijeet Rastogi


People also ask

Does bash use fork or exec?

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.

What is fork bash?

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.

What is exec in bash?

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.

What is exec and fork in Linux?

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.


1 Answers

Use the ampersand just like you would from the shell.

#!/usr/bin/bash function_to_fork() {    ... }  function_to_fork & # ... execution continues in parent process ... 
like image 74
mob Avatar answered Oct 04 '22 06:10

mob