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
Related
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
}
I want to make two parallel working forks and in the end wait for them to finish.
for (int i = 0; i < 2; i++) {
pid_t pid = fork();
if(pid < 0) {
fprintf(stderr,"Cannot fork!");
exit(EXIT_FAILURE);
}
else if(pid == 0) {
switch(i)
{
case 0:
//first child
exit(EXIT_SUCCESS);
break;
case 1:
//second child
exit(EXIT_SUCCESS);
break;
}
break;
}
else {
//parent
}
}
The problem is that the main program terminates before the child ones. If I add wait(0) to the else parent part it waits to every process so they don't work at the same time but one by one.
I assumed that I can simply put the wait() or waitpid() after the loop but that's not working either. I thought that after the fork the parent continues normally so why doesn't it wait when the wait() is outside the loop and if-else structure?
Sorry for bothering and thanks in advance.
If you add wait(NULL) inside the else parent part, the parent-process will indeed wait for the first child-process to return before it creates the second.
If you add wait(NULL) after the loop, the parent process will wait only once, for the first child-process that will return.
If you want all children-processes to run at the same time, you need a second loop, where the parent-process will use wait() as many times as needed to collect the exit status of every child-process.
In your case, there are 2 children-processes, thus 2 wait() system calls are enough. The loop to add would be like this (I also added a printf so that you can observe it on your stdout):
for (i = 0; i < 2; i++) {
wait(NULL);
printf("My child No %d died.\n", i);
}
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
}
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();
}
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
}