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).
Related
I'm studying how fork() actually works so my code below has no purpose other than spawning new processes with fork() and see them die randomly. So:
I put my fork() in a for loop (to run twice for now) to see more than one child be created, and to my surprised it seems that the second Child has a parent that was not the same parent as the first child. So, if my initial PID was 1000, the two child created would be 1002 (child of 1000) and 1003 (child of 1001???). I didn't understand what happened that a parent was created. This guy explained but I can't say I fully understood.
To try and find out what was going on, I printed my parent (and child) processes with their PID, but if I declare a char for my parent, my child won't run the function. I explain what I mean in my code between <<< >>>.
So, can anyone help me understand my 1st point, and identify why 2 is happening?
Full code below:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
const int PASS = 5;
const int RANDLIMIT = 5;
const int FORKNUMBER = 2;
int i = 0;
void doSomeWork(char *who);
int main(int argc, char *argv[])
{
printf("Just started, I am: %d\n", (int) getpid());
int j;
pid_t pid;
for (j=0; j < FORKNUMBER; j++)
pid = fork();
printf("fork returned: %d\n", (int) pid);
srand((int) pid + rand());
if (pid < 0) {
perror("fork failed");
} else if (pid == 0) {
char * childPid;
char * childName;
sprintf(childPid, "%d", (int) getpid());
childName = (char *) malloc(strlen("Child - ") + strlen(childPid) + 1 );
strcpy(childName, "Child - ");
strcat(childName, childPid);
doSomeWork(childName);
exit(0);
}
//<<< The malloc above for the child to send a parameter >>>
//<<< to the function, works fine. But when I try to do >>>
//<<< the same for my parent, the simple declaration of a>>>
//<<< char below, makes the child block (the if PID==0) >>>
//<<< not run. The 3 lines commented below were an >>>
//<<< attempt to understand what was preventing the child>>>
//<<< block from running. Now, if the parent calls the >>>
//<<< function with a string not declared before, the >>>
//<<< child block runs fine.>>>
//char parentName[strlen("Parent") + 1];
//strcpy(parentName, "Parent");
//doSomeWork(parentName);
doSomeWork("Parent");
//wait(NULL);
return(0);
}
void doSomeWork(char *who)
{
int control = 0;
for(; i < PASS; i++){
sleep(rand() % RANDLIMIT);
printf("%s: Done pass #%d, my parent = %d\n", who, i, getppid());
if (control == 0)
{
char childWord[6];
strncpy(childWord, who, 5);
if (strcmp(childWord, "Child") == 0 && (int) getppid() == 1 )
{
control = 1;
printf("%s: became orphan at #%d\n", who, i);
}
}
}
printf("%s: exiting...\n", who);
}
EDIT:
For 1, I created a function like below:
int nbDigits(int number)
{
int i=0;
for(; number > 10; i++)
{
number /= 10;
}
return ++i;
}
Now instead of declaring a pointer to a char like this, char * childPid; I declared a char array like this char childPid[nbDigits(getpid()) + 1]; and everything worked like a charm.
Check out Joseph's suggestion below using asprintf(), seems neat.
You can't call fork() in a loop but only check what it returns at the end of the loop if you want your program to work. When you do so, you're starting an exponential number of child processes, and each one thinks it's "the parent" as long as it was the parent of its final fork(). Move your test of pid to inside the loop.
char * childPid;
sprintf(childPid, /* ... */);
That's going to clobber some random memory. You need to point childPid to something before you sprintf to it, or replace sprintf with something like asprintf that will allocate itself.
As soon as you run fork() any child process will start its execution from there.
Fork system call use for creates a new process, which is called child
process, which runs concurrently with process (which process called
system call fork) and this process is called parent process. After a
new child process created, both processes will execute the next
instruction following the fork() system call. source
Thus, when your first iteration happens (i=0) there will be a new process, with a new pid, and then, both parent and this child process will call the next iteration (i=1) and create a new child for each one with two more new pid. In the end, you will have 4 different pid.
Example
Parent process pid=1000
i = 0, creates pid=1001, now you have both 1000 and 1001
i = 1, creates a child from 1001 -> 1002 and a child from 1000 again, 1003.
In the end you have 1000, 1001, 1002 and 1003 and all of these four processes will run the following instruction which is the printf.
So I am trying do a application which fork()s 2 children.
first does a for(i=1; i<=50000; i++) loop
the second a for(i=50000; i<=100000; i++) loop
the parent does for(asciic=65; asciic<=90; asciic++)-> loop for printing A to Z letters
I need all three to do they're work simultaneous not one after another.
I've looked over the internet and I couldn't found a proper way, all I could find are loops which create the children processes but they do almost the same thing and most are created one after another.
Any help is appreciated.
To be more understood, this is what I've done before posting:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
pid_t child_pid,child_pid1;
int i=0;
int stare;
int asciic;
child_pid=fork();
child_pid1=fork();
if (child_pid==0) {
//printf("Father PID: %d -> Child 1: %d\n",getppid(),getpid());
for(i=1; i<=50000; i++){
printf("%d-%d\n",getpid(),i);
}
exit(0);
} else if (child_pid1==0) {
//printf("Father PID: %d -> Child 2: %d\n",getppid(),getpid());
for(i=50000; i<=100000; i++) {
printf("%d-%d\n",getpid(),i);
}
exit(0);
} else {
//printf("PID-ul procesului parinte: %d\n", getpid());
pid_t rez=waitpid(child_pid,&stare,WNOHANG);
pid_t rez1=waitpid(child_pid1,&stare,WNOHANG);
while(rez==0 || rez1==0){
for(asciic=65; asciic<=90; asciic++){
printf("%d- %c\n",getpid(),asciic);
}
rez=waitpid(child_pid,&stare,WNOHANG);
rez1=waitpid(child_pid1,&stare,WNOHANG);
}
}
return 0;
}
If I comment out the loops I can see that the children have different PIDs, 1 child has the right parent PID and other it has other parent PID.
Your 2 lines with forks:
child_pid=fork();
child_pid1=fork();
do not create 2 children, but three: the parent creates a first child in the first fork(). From that moment there are 2 processes: parent and child. And each of them executes the second fork(). You will have in total 1 parent, 2 children and 1 grandchild.
In order to have just 1 parent and 2 children, you will have to:
pid1 = fork();
if (pid1 < 0) {
/* Error in fork() */
} else if (pid1 == 0) {
/* first child */
exit(0);
}
pid2 = fork();
if (pid2 < 0) {
/* Error in fork() */
} else if (pid2 == 0) {
/* second child */
exit(0);
}
/* parent */
Moreover, even when your code is correct, you cannot "see" if the processes are running concurrently or not just looking at their outputs. In fact, even if there are multiple processes executing "at the same time", you may see that one of the processes finishes before another one starts. That is because typically the kernel does time multiplexing to offer each child some CPU time. You can see concurrency if the processes take longer to complete, for example adding some sleep().
The problem is here:
child_pid=fork();
child_pid1=fork(); // This line will be executed by both parent and first child!!!
You need to move the second fork into the parent part of the first if, and then have a separate if for the second child.
fork() returns the pid_t of the child to the caller (parent), or -1 if it failed. In the child, 0 is returned. You can simply test
if (fork())
{
//do one thing
}
else
{
//do something else
}
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;
}
So I have the following C code:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(){
int i = 0, n;
n = 5;
pid_t pid;
printf("i=%d Right before the loop\n", i, getpid(), getppid());
for (i = 0; i < n; i++){
pid = fork();
if (pid <= 0){
printf("something happens in loop #%d. pid = %d\n", i, pid);
break;
}
printf("End of loop #%d\n", i);
}
printf("i=%d My process ID = %d and my parent's ID = %d\n", i, getpid(), getppid());
return 0;
}
I have only one question:
Why does
printf("i=%d My process ID = %d and my parent's ID = %d\n", i, getpid(), getppid());
get executed many times as if it was inside the loop? I have tried to figure out through so many ways but I cannot find the reason.
The reason is that fork() works by making a child process that is a copy of the parent that starts running at the fork() call. So every child process runs that printf command.
Example:
Here's a less complicated example:
#include <stdio.h>
int main(){
int pid = fork();
if (pid == 0){
// child code
printf("child pid: 0\n");
}else{
// parent code
printf("parent pid: %d\n", pid);
}
// executed by both
printf("This text brought to you by process %d.\n", pid);
}
You have to do something like this if you want to restrict some code to only be run by the child or parent.
On my machine, when I just ran it, it outputs:
parent pid: 12513
This text brought to you by process 12513.
child pid: 0
This text brought to you by process 0.
My operating system ran the parent process first, but it didn't have to.
If you are not aware of fork() and using it, it is dangerous.
This is one of the basic system calls in Linux used for creating a new process. Refer to Man page to know what it does. And here is one helpful link to make you understand better. fork().
To know more about it you could also refer here- fork() wiki. It uses methods like copy-on-write and shares the resources with child.
Once you have used fork() to create the new process, you can use exec(...) to change the program that the process is executing. After reading about each of them, you may refer to this post on so.
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.