Spawn multiple children processes - c

So I want to spawn a number of children processes equal to a value inputted from the command line. I have all the values and everything reading in just fine, I just need to figure out how to spawn these children, and have them all call the same program.
Here is what I have so far:
for(int i = 0; i < processes; i++)
{
pid = fork();
printf("%d\n", pid);
}
if(pid < 0)
{
perror("fork");
exit(-1);
}
else if(pid == 0)
{
/*for(int j = 0; j <= 5; j++)
{
execl("~/cs370/PA2/gambler.c","run", NULL);
Gamble(percent);
}*/
}
So to be clear again. I want to spawn "processes" amount of children, that all call "gambler.c". But ONLY 5 can be running at a time. It should wait(), and then process the rest of the children 5 at a time.
Sample input:
run -p 60 10
Where -p is a percentage to be fed to gambler.c which just returns success or failure based on a random number generator. 60 is the percentage. 10 is the number of processes.
Any help is much appreciated thanks!

Have you looked into the exec family? Exec will spawn processes. You can then use wait to monitor the processes. fork will give you the PID and you can then have a second thread loop over each pid calling wait and keeping track of each active process.
wait man page
exec man page
pid_t pid = fork()
if (pID == 0)
{
//child
//immediatly call whichever exec you need. Do not do anything else.
//do not log a message or print a string. Any calls to c++ standard strings
//will risk deadlocking you.
}
else if (pid < 0)
{
//error
}
else
{
//parent. store pid for monitoring
}

Related

C, Creating multiple process with same parent [duplicate]

can someone help me about how to create multiple child processes which have the same parent in order to do "some" part of particular job?
for example, an external sorting algorithm which is applied with child processes; each child process sorts a part of data and finally the parent merges them..
EDIT: Maybe I should mention the forking multiple child processes with loop..
Here is how to fork 10 children and wait for them to finish:
pid_t pids[10];
int i;
int n = 10;
/* Start children. */
for (i = 0; i < n; ++i) {
if ((pids[i] = fork()) < 0) {
perror("fork");
abort();
} else if (pids[i] == 0) {
DoWorkInChild();
exit(0);
}
}
/* Wait for children to exit. */
int status;
pid_t pid;
while (n > 0) {
pid = wait(&status);
printf("Child with PID %ld exited with status 0x%x.\n", (long)pid, status);
--n; // TODO(pts): Remove pid from the pids array.
}
If you want to launch several forks, you should do it recursively. This is because you must call fork from the parent process. Otherwise, if you launch a second fork, you will duplicate both parent and first child process. Here's an example:
void forker(int nprocesses)
{
pid_t pid;
if(nprocesses > 0)
{
if ((pid = fork()) < 0)
{
perror("fork");
}
else if (pid == 0)
{
//Child stuff here
printf("Child %d end\n", nprocesses);
}
else if(pid > 0)
{
//parent
forker(nprocesses - 1);
}
}
}
I think it would be worth pointing out why threads are more appropriate here:
As you are trying to do a "part" of the job in parallel i assume that your program needs to know about the result of the computation. fork()s of a process don't share more then the initial information after fork(). Every change in one process is unknow to the other and you would need to pass the information as a message (e.g. through a pipe, see "man pipe").
Threads in a process share the same adress space and therefor are able to manipulate data and have them visible toeach other "immediatly". Also adding the benefits of being more lightweight, I'd go with pthreads().
After all: You will learn all you need to know about fork() if you use pthreads anyway.
You can do this with fork. A given parent can fork as may times as it wants. However, I agree with AviD pthreads may be more appropriate.
pid_t firstChild, secondChild;
firstChild = fork();
if(firstChild > 0)
{
// In parent
secondChild = fork();
if(secondChild > 0)
{
// In parent
}
else if(secondChild < 0)
{
// Error
}
else
{
// In secondChild
}
}
else if(firstChild < 0 )
{
// Error
}
else
{
// In firstChild
}

fork exec wait loop for a command line entered value

I'm trying to exec a file within another file for maximum 5 times and save results. I use a fork-exec-wait in a for loop, this is how it looks like:
for(i = 0; i< Number_of_Processes; i++){
pid = fork();
if(pid == 0)
{
execl(...);
exit(EXIT_Failure);
}
else if(pid > 0)
{
wait(&status);
result = WEXITSTATUS;
}
}
The problem is, it executes the second file for first time correctly and then reprints the first result for 5 times(or whatever the user entered)
I tried so many other ways, like break when it's pid == 0 but it didn't work. i couldn't find a proper example of how to use exec within a loop so I'm stuck for hours, trying moving functions up and down and get nothing.
Whatever i do, i can't see a second execution of the inner file.
Apparently it was a problem of timing, when i add a sleep(1) just before execl in child process, it fixed everything and execed needed processes one by one and printed true results
for(i = 0; i< Number_of_Processes; i++){
pid = fork();
if(pid == 0)
{
sleep(1);
execl(...);
exit(EXIT_Failure);
}
else if(pid > 0)
{
wait(&status);
result = WEXITSTATUS;
}
}

multiple processes using fork()

I'm using this to set up a process in my main:
pid = fork();
if (pid == 0)
ChildProcess();
else
ParentProcess();
How would I go about setting more processes, say for example x4 of them?
If you're in the parent process, call fork() again to get another child. If you put it in a loop then you're golden.
for (int i = 0; i < 4; ++i) {
pids[i] = fork();
if (pids[i] == 0) {
ChildProcess();
break;
}
}
Make sure the child does not call fork(). Only the parent.
There is some ways to do this.
For example:
1. just repeate your fork() for 4 times.
2. use a loop to call fork() for 4 times.
3. wrapps those into a functions

C - meaning of wait(NULL) when executing fork() in parallel

In the code below, do the forks actually run in parallel or one after another?
What is the meaning of wait(NULL) ?
(The program creates an n number of child processes, n is supplied via command line)
int main ( int argc, char *argv[] ) {
int i, pid;
for(i = 0; i < atoi(argv[1]); i++) {
pid = fork();
if(pid < 0) {
printf("Error occured");
exit(1);
} else if (pid == 0) {
printf("Child (%d): %d\n", i + 1, getpid());
exit(0);
} else {
wait(NULL);
}
}
}
They do run in parallel, up until the point that one of them waits.
wait(NULL) or more accurately wait(0) means wait until a state change in the child process. To find out about Unix / Linux C api calls, type man <function Name> on the command line. You'll need to get used to reading those pages, so better start now.
In your case
man wait
would have given you what you needed.
Since you've only fork(...)ed once, you have only one child. The parent waits until it changes state, and since the child's state during the fork is the same as the parent's state prior to the fork (that of running), the likely outcome is that the parent waits until the child dies. Then the parent will continue executing, but since it doesn't have much to do after the wait(...) call, it will quickly exit too.

Preventing grand children from forking in C

I have the following code in which I'm trying to create sub processes by forking. I want that exactly 3 sub processes are made. However, when I run the code I seem to be getting more, probably because of the children processes forking grandchildren. What am I missing here, how can I prevent this.
Code:
for(j = 0; j < 3 ; j++){
if((pid = fork()) == 0){ // child process
dosomething();
exit(0); // terminate child process
}
else if((pid = fork()) > 0){
printf("I'm in parent of the client spawn loop\n");
// exit(0);
}
}
Output:
I'm in parent of the client spawn loop
I'm in parent of the client spawn loop
I'm in parent of the client spawn loop
I'm in parent of the client spawn loop
I'm in parent of the client spawn loop
I'm in parent of the client spawn loop
I'm in parent of the client spawn loop
Don't do the second fork call as it will create a new child. The first is enough:
for (j = 0; j < 3; ++j)
{
pid_t pid = fork();
if (pid == 0)
{
printf("In child (j = %d)\n", j);
exit(0);
}
else if (pid > 0)
{
printf("In parent (j = %d)\n", j);
}
}
Will print "In child" three times, with j equal to 0, 1 and 2. The same for the parent printing.
In your real code you should check for errors though.
Don't call fork() more than once in the loop.
The parent shouldn't call fork() again, that will create yet another child and introduce another child-parent split point.
You should have, in the loop:
const int pid = fork();
if(pid == 0)
{
doSomething();
exit();
}

Resources