77

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.

shadyabhi
  • 16,675
  • 26
  • 80
  • 131

2 Answers2

127

Use the ampersand just like you would from the shell.

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

function_to_fork &
# ... execution continues in parent process ...
mob
  • 117,087
  • 18
  • 149
  • 283
  • 5
    This is not exactly the same as "fork". I test some command using fork in C or Ruby, and it runs well. But using "&" like above, it fails. – user180574 Sep 21 '15 at 17:05
  • Nice, but... I generally fail when I try to use a function. I use a separate script and call it. Much more versatile. The redirect and background functionality is more intuitive and can be more easily tested from the command line. – nroose Mar 02 '16 at 22:54
  • Clarification for wording: What is described in this answer is essentially executing a subshell in the background. "fork() and exec()" is what bash does every time you call a binary. But this is done in the foreground, blocking the script execution. When you do this in a subshell you get the behavior asked for in the question. See Section 3.2.3 of the Bash Reference Manual. – heine Oct 15 '20 at 13:31
40

How about:

(sleep 5; echo "Hello World") &
Jubal
  • 8,357
  • 5
  • 29
  • 30
  • 2
    @staticx Meaning that the process will fork, but the parent will not continue executing until the `()` returns? – msanford Aug 15 '14 at 20:00
  • @Brian this doesn't wait for me, just forks – BryanK Aug 06 '16 at 04:26
  • this means that u fork and also track the return status code if u need to – Dragonborn Sep 06 '18 at 22:38
  • 1
    This is really what you need when you need this. Most of the time you can just background the new process. But if you need to background a complex process this is great. – Bday Jul 06 '20 at 18:16