1

How can I do this?

I just wish to write something like

while(true) {
fork()
}

Is this possible in bash ? I don't want it for religious reasons, just to explain to a friend!

Ryan Giggs
  • 13
  • 2

2 Answers2

3

Try this:

#!/bin/bash
$0 &
$0 &
wait

Optionally insert echo $$ before the first $0

Erik
  • 88,732
  • 13
  • 198
  • 189
  • Starting /bin/bash and placing it in the background seems to cause the bash process that was just placed in the background to stop until it has been brought back into the foreground. – Suroot Mar 22 '11 at 23:05
  • Hmmm, interesting; I was merely looking at it from the bash point of view; not as a script itself. Yes indeed it does work. – Suroot Mar 22 '11 at 23:19
1

You cannot do it by bash alone since there isn't a fork() system call directly accessible in bash (at least as far as I can tell). You could do a 1 liner in Perl though.

perl -e 'while(1) { fork(); sleep(1); }'

This should spawn 2xnumber of processes per second. I.E. first spawn will give you 2, next run gives you 4, next run gives you 8 etc...

Suroot
  • 4,315
  • 1
  • 22
  • 28
  • Is there any way I could create a simple call to fork() in a neverending loop in terminal ? I am really just trying to teach him the meaning of fork(), and making it interesting is difficult! – Ryan Giggs Mar 22 '11 at 23:08
  • I'm not sure what you're trying to accomplish and what the difference is. The perl script will crash your machine just the same as creating a C application to do the exact same functionality. – Suroot Mar 22 '11 at 23:13
  • You *can* do this in `bash`. Whether you *should* (in `bash` or `perl` or `logo`...) is another question! – johnsyweb Mar 22 '11 at 23:27