i've been making google searches about my question for 2 days but im done with it. I have very basic information about process management, fork etc. I've been told to create some children processes of a same parent process and send them seeds by using pipes so they can produce some random numbers, all for their own. But I'm stuck at creating children processes.
for (i = 0; i < NUM_PLAYERS; i++) {
/* TODO: spawn the processes that simulate the players */
switch(pid = fork()){
case -1: // ERROR
exit(EXIT_FAILURE);
case 0: // CHILD PROCESS
printf("My parent id is %d \n", getppid());
exit(EXIT_SUCCESS);
default: // PARENT PROCESS
wait(NULL);
}
}
When I go with this code, parent creates NUM_PLAYERS children but I can't seem to use them in another for loop since they had terminated at the end of the case 0. When I just remove exit(EXIT_SUCCESS); line, so many processes are created and they have all different parents. So my question is, how to properly create children processes and use them later?
If you remove exit(EXIT_SUCCESS) your child will continue executing where it was forked, IE it will go back to the close brace of the for() loop, and generate new children itself. What do you want the child to do? You should make it do that, and then do exit(EXIT_SUCCESS) and not let it return to to the for() loop.
Note also that wait() will only wait for one process to quit.
void do_something()
{
//create random numbers or whatnot
}
//...........
case 0: // CHILD PROCESS
printf("My parent id is %d \n", getppid());
do_something();
exit(EXIT_SUCCESS);
You'll need the parent to wait on the children in a later loop. The way you have it will block until a single child returns. You want to create multiple children before then waiting on them.
Note that you still have to add the pipe logic so parent/child can communicate.
EDIT
This is the broad outline of what you need to do:
for (i = 0; i < NUM_PLAYERS; i++) {
/* TODO: spawn the processes that simulate the players */
switch(pid = fork()){
case -1: // ERROR
exit(EXIT_FAILURE);
case 0: // CHILD PROCESS
printf("My parent id is %d \n", getppid());
exit(EXIT_SUCCESS);
}
}
// only the parent will ever execute below here
for (i = 0; i < NUM_PLAYERS; i++)
{
while ( /* read each child's pipe*/)
{
//do something with data
}
}
for (i = 0; i < NUM_PLAYERS; i++)
wait(NULL);
return(0);
Related
Good afternoon.
I am currently working on a C program that takes one and only one parameter which designates the number of "child generation"s to be created (the own father counts as 1 already). "wait()" system calls are not to be used for this exercise (the version with "wait" calls happens to work exactly as expected).
For instance, the call $program 4 should generate a hierarchy like this:
Process A creates B
Process B creates C
Process C creates D
The printed messages are not important, as they are merely orientative for the task. With the following code (which happens to work exactly how I want with a "wait()" call) states that all the child processes derive from the same father, which I don't understand why it's happening.
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
int counter; pid_t result; int i;
/*
We are going to create as many processes as indicated in argv[1] taking into account that the main father already counts as 1!
*/
if (argc > 2 || argc == 1) {puts("IMPOSSIBLE EXECUTION\n"); exit(-1);}
int lim = atoi(argv[1]);
//We eliminate the impossible cases
if (lim < 1) {puts("IMPOSSIBLE EXECUTION\n"); exit(-1);}
if (lim == 1) {puts("The father himself constitutes a process all by his own, therefore:\n");
printf("Process%d, I'm %d and my father: %d\n", counter, getpid(), getppid());
}
else {
for (i = 0; i < lim; i++) {
result = fork();
if (result < 0) {
printf("Call%d \n", counter); perror("Has failed!");
exit(-1);
}
else if (result) {
break; //Father process
}
else {
counter++; //Child processes increment the counter
printf("Process%d, I am %d and my father: %d\n", counter, getpid(), getppid());
}
}
}
The hierarchy generated by the code above is not the one I expected...
All help is greatly appreciated.
Thank you
With the following code (which happens to work exactly how I want with
a "wait()" call) states that all the child processes derive from the
same father, which I don't understand why it's happening.
I don't see that in my tests, nor do I have any reason to expect that it's actually the case for you. HOWEVER, it might appear to be the case for you if what you see is some or all of the child processes reporting process 1 as their parent. That would happen if their original parent terminates before the child's getppid() call is handled. Processes that are orphaned in that way inherit process 1 as their parent. If the parent wait()s for the child to terminate first then that cannot happen, but if instead the parent terminates very soon after forking the child then that result is entirely plausible.
Here's a variation on your loop that will report the original parent process ID in every case:
pid_t my_pid = getpid();
for (i = 0; i < lim; i++) {
result = fork();
if (result < 0) {
printf("Call%d \n", counter); perror("Has failed!");
exit(-1);
} else if (result) {
break; //Father process
} else {
pid_t ppid = my_pid; // inherited from the parent
my_pid = getpid();
counter++; //Child processes increment the counter
printf("Process%d, I am %d and my father: %d\n", counter, (int) my_pid, (int) ppid);
}
}
You are missing a crucial function call.
for (i = 0; i < lim; i++) {
fflush(stdout); // <============== here
result = fork();
Without it, your fork duplicates parent's stdout buffer into the child process. This is why you are seeing parent process output repeated several times --- its children and grandchildren inherit the output buffer.
Live demo (with fixed formatting for your reading convenience).
I want to create a program in C, where I use fork() to create multiple children, then wait for all of them to finish and do parent code (only once).
I tried using for loop and two forks but I there is a problem: either parent code isn't running at the end or children are not running parallel.
//Number of processes I want to create
int processes = 6;
pid_t *main_fork = fork();
if(main_fork ==0){
for(int i=0;i<processes;i++){
pid_t *child_fork = fork();
if(child_fork ==0){
// child code
exit(0);
}
else if(child_fork >0){
//And here is the problem, with the wait: children don't
//run parallel and if I delete it, the main parent code doesn't run
wait(NULL);
}else{
// Child fork failed
printf("fork() failed!\n");
return 1;
}
}
}else if(main_fork >0){
wait(NULL);
//Main parent code - here I want to do something only once after all
//children are done
}else{
// Main fork failed
printf("fork() failed!\n");
return 1;
}
If somebody could could fix my code, or write a better solution to this problem I would be so grateful!
If you want all the children to run in parallel, you have to do the wait after all the children has been started. Otherwise you start a child, wait for it to finish, start a new one, wait for that to finish, start a third one, wait for the third one to finish, and so on...
So what you typically want to do is to start all the children and put all the pid_t in an array, and when you are finished you may call wait() for each pid_t
This is the simple, and good enough solution for your case.
Here is a sample code that you can fit to your problem:
pid_t children[processes];
for(int i=0; i<processes; i++)
{
pid_t child = fork();
if(child == 0)
{
// child code
....
// We call _exit() rather than exit() since we don't want to clean up
// data structures inherited from parent
_exit(0);
}
else if (child == -1)
{
// Child fork failed
fprintf(stderr, "myprog: fork failed, %s", strerror(errno));
// Do real cleanup on failure is to complicated for this example, so we
// just exit
exit(EXIT_FAILURE);
}
children[i] = child;
}
// Do something if you want to do something before you expect the children to exit
....
for(int i=0; i<processes; i++)
{
pid_t child = children[i];
int status;
waitpid(child, &status, );
// Do something with status
}
Naturally this is not a complete example that fits any situation. Sometimes you have to tell the children when they should exit. Other times the children are not started/stopped in one go, and you have to play with asynchronous events, and so on...
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);
}
Goodmorning, i would like to ask 2 things..
1) what returns a fork() did on a child which has already a pid==0 ? if i continue to fork on every son, each of them will have 0 as pid ?? or not ?
2) this is my file Buffer.c and it runs on a single process.
At the beginning it forks() out some Producers who produce() and some Consumers who consume() ,but I am afraid that every producers enters in the next for cicle and it starts to produce himself other consumers!! because it write pid=-1 so...
I want that this piece of code produce only P producers and C consumers, but i need to know why every producer do not create other consumers!
Can you help me,maybe giving me a scheme of how many processes i will create with this code?
Maybe doing a scheme as this:
Father:
8 producers
-
-
-
...
each of them produces: 5 consumers
etc etc......
int main(int argc, char **argv) {
/....
pid_t pid;
pid_t cons_pid[C];
/* fork producers */
pid = -1;
for(i=0; i<P && pid!=0; i++)
pid=fork();
switch(pid) {
case -1:
...
case 0:
/* GENERIC PRODUCER i */
...
/* PRODUCE() */
printf("Producer %d exits\n",i);
...
return 0;
}
/* fork consumers */
pid = -1;
for (j=0; j<C && pid!=0; j++)
pid = cons_pid[j] = fork();
switch(pid) {
case -1:
....error
case 0:
/* GENERIC CONSUMER j */
CONSUME()....
}
return 0;
}
what returns a fork() did on a child which has already a pid==0
0 is not a valid PID, hence by definition there can't be an process with PID=0 and thus PID=0 is a perfectly well defined return for indicating child status.
if i continue to fork on every son, each of them will have 0 as pid
No process ever has PID=0. All PIDs are greater than zero! A zero is just the return value received by the newly forked process to indicate that it's the child. The actual PID a child process got is queried using the getpid function from the child process. However the parent process can't perform such a query, since in the time between fork and a assumed query function call, the child may already have terminated (race condition). So you want fork to return the PID to the parent directly.
BTW: The terminology is parent and child not father and son (processes are things not people, despite what the TRON movies depict).
Regarding your code snippet: A switch statement is the wrong choice here. You want to use an if statement.
fork() splits up the current process into a father and a child. The child will have a new PID, the father retains the old PID. In both processes fork() returns after the splitting. In the father the return value will be the PID of the child (to make it known), and in the child the return value will be 0.
1) The lowest possible process ID is 1, this is the ID of the init process from which all other processes are forked. Therefore, it is not possible for a child or for your parent process to "already have ID 0". Your child's process ID is necessarily greater than 1. Thus, the problem that you are afraid of cannot happen.
2) The confusion that you state is the reason why fork (which returns twice, once for the parent and once for the newly created child!) has a somewhat "weird" return value which can have so many different values:
it can be -1, then something went wrong, and no child was created.
it can be a positive value, then you are in the parent process, and the value is the child's process ID. It's as if you called any other "normal" function that just returned normally.
it can be 0, then your code knows it is now running in the child process.
You must examine the return value (if()) so you know what process you are in. Then no such thing as you decribe can happen (or, should happen, this presumes your code does not have any bugs).
EDIT:
The code can be rewritten slightly so it gets rid of the && pid!=0 inside the loop and thus looks a bit less scary overall:
int main()
{
int pid, i;
pid_t cons_pid[C];
for(int i=0; i<P; ++i)
{
pid=fork();
if(pid == -1) exit(1); /* fork error */
if(pid == 0) { producer(); return 0; }
}
for(i=0; i<C; ++i)
{
pid = fork();
if(pid == -1) /* fork error */
{ /* should do a kill_producers(); here */ exit(2); }
else if(pid == 0) /* consumer */
{ consumer(); return 0; }
else /* master process, remember all consumer pids */
{ cons_pid[j] = pid; }
}
/* ... */
return 0;
}
I'm currently writing a simple C program to create a specified number of child-processes from the parent process, and I'm trying to keep track over how many of them that was actually successfully initiated by increasing the variable active every time a child-process was successful.
However, the stupid piece of #!%€ variable won't let me modify it.. I'm new to C (hence the simplicity and questionable usability of the program) and I'm having a bit of a problem understanding the different variable-scopes and when, and how you can modify them so that the new value sticks...
So, my questions is; how do I make the variable "active" increase by 1?
I've already made sure that the newChild() function returns 1 as it should, and other code within that if-statement works, so it's not that. And, I've also tried using pointers, but without success... :(
# include <stdio.h>
# include <unistd.h>
# include <stdlib.h>
# include <sys/wait.h>
main()
{
printf("Parent CREATED\nRunning code...\n");
// INITIATE Variables
int children = 5;
int active = 0;
int parentID = getpid();
// INITIATE Random Seed
srand(time(NULL));
// CREATE Children
int i, cpid, sleepTime;
for (i = 0; i < children; i++)
{
// Only let the parent process create new children
if (getpid() == parentID)
{
// GET Random Number
sleepTime = rand() % 10;
// CREATE Child
if (newChild(sleepTime) == 1)
{
// Mark as an active child process
active++;
}
}
}
// CLEAN UP
if (getpid() == parentID)
{
// Let the parent process sleep for a while...
printf("Parent is now SLEEPING for 20 seconds...\n");
sleep(20);
printf("Parent is now AWAKE\nActive children: %d\n", active);
// WAIT for Children
int cpid, i;
int status = 0;
for (i = 0; i < active; i++)
{
// WAIT for Child
cpid = wait(&status);
// OUTPUT Status
printf("WAITED for Child\nID: %d, Exit Status: %d\n", cpid, status);
}
printf("All children are accounted for.\nEXITING program...\n");
}
}
int newChild(int sleepTime)
{
// INITIATE Variable
int successful = 0;
// CREATE Child Process
int pid = fork();
if (pid == -1)
{
// OUTPUT Error Message
printf("The child process could not be initiated.");
}
else if (pid == 0)
{
// Mark child process as successfully initiated
successful = 1;
// OUTPUT Child Information
printf("Child CREATED\nID: %d, Parent ID: %d, Group: %d\n", getpid(), getppid(), getpgrp());
// Let the child process sleep for a while...
printf("Child %d is now SLEEPING for %d seconds...\n", getpid(), sleepTime);
sleep(sleepTime);
printf("Child %d is now AWAKE\n", getpid());
}
return successful;
}
There are three outcomes from calling fork() which your code is incorrectly condensing down to two:
A return value of -1 indicates that fork failed. This is an uncommon error condition.
A return value of 0 indicates that fork succeeded and you're now in the child process.
A return value of >0 indicates that fork succeeded and you're in the parent process.
Notice how cases 2 and 3 are both "successful". But your newChild() function returns 1 for case 2 and returns 0 for case 3. Instead what it should do is return 1 for case 3, and for case 2 it shouldn't even return. If you're in case 2 then you're in the child process and so you should just do your child process stuff and then exit, never returning to the caller.
if (pid == -1)
{
// OUTPUT Error Message
printf("The child process could not be initiated.");
}
else if (pid == 0)
{
// OUTPUT Child Information
printf("Child CREATED\nID: %d, Parent ID: %d, Group: %d\n", getpid(), getppid(), getpgrp());
// Let the child process sleep for a while...
printf("Child %d is now SLEEPING for %d seconds...\n", getpid(), sleepTime);
sleep(sleepTime);
printf("Child %d is now AWAKE\n", getpid());
// This is the child process, so we should NOT EVEN RETURN from newChild().
exit(0);
}
else
{
successful = 1;
}
The key observation here is that when you call fork() your process is going to split into two separate processes that both continue executing from the point where fork() returns. The difference between them is that one will get a 0 return value and the other will get a >0 return value. The former is the child and the latter is the parent.
After fork() you now have two copies of the same code running, with two separate invocations of newChild() running, and with two separate copies of the active variable. After forking there are two of everything.