How do you use the fork() command in such a way that you can spawn 10 processes and have them do a small task concurrently.
Concurrent is the operative word, many places that show how to use fork only use one call to fork() in their demos. I thought you would use some kind of for loop but i tried and it seems in my tests that the fork()'s are spawning a new process, doing work, then spawning a new process. So they appear to be running sequentially but how can I fork concurrently and have 10 processes do the work simultaneously if that makes sense?
Thanks.
Update: Thanks for the answers guys, I think I just misunderstood some aspects of fork() initially but i understand it now. Cheers.
Just loop in the "main" process spawning one child after another with each assign a particular task.
You might also want to look into POSIX Threads (or pthreads). Here is a tutorial:
https://computing.llnl.gov/tutorials/pthreads/
Call
fork()
in a loop:Adding code to wait for children per comments:
When you fork off processes the WILL be running concurrently. But note that unless you have enough available idle processors, they might not actually be executing concurrently, which shouldn't really matter...
Your second paragraph makes it seem like you aren't understanding how fork works, you have to check the return code to see if you are in the parent or in the forked process. So you would have the parent run a loop to fork off 10 processes, and in the children you do whatever you wanted to do concurrently.