fork and exec in bash

LinuxBashScriptingShell

Linux Problem Overview


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.

Linux Solutions


Solution 1 - Linux

Use the ampersand just like you would from the shell.

#!/usr/bin/bash
function_to_fork() {
   ...
}

function_to_fork &
# ... execution continues in parent process ...

Solution 2 - Linux

How about:

(sleep 5; echo "Hello World") &

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAbhijeet RastogiView Question on Stackoverflow
Solution 1 - LinuxmobView Answer on Stackoverflow
Solution 2 - LinuxJubalView Answer on Stackoverflow