While going thorough fork() command i got struck with a question .
how many no.of processes are created by the end of 12th second, if
time starts from 0th second? Process id's start from 0.
Pseudo code
while(true)
{
sleep 1second;
if( getpid() % 2 == 0 )
{
fork();
printf("Hello\n");
}
}
when i run above code on my system it is not showing output on konsole. Is no . of process at end of 12 sec is dependent on OS ?Need suggestion as i am not good in fork()
Since when do process IDs "start at 0"? Not even when the system boots; the first process has the id 1 :-)
You're only fork()ing when your own process ID is even; so if it happens to be odd then nothing will happen... which means that if you run the program several times, sometimes it will do something and sometimes it won't.
Add this after your printf:
fflush(stdout);
But you have a fundamental problem with your logic. fork() returns 0 in the child, and the child pid in the parent. You don't check, so both the parent and the child continue doing the loop, which happens again, and again, and again, forever. You need to change the loop body to this:
if(fork() == 0)
{
printf("Hello!\n");
fflush(stdout);
}
Related
The output of the program are not obviously contents from the printf()s in teh code. Instead it looks like characters in irregular sequence. I know the reason is because the parent process and child process are running
at the same time, but in this program I only see pid=fork(), which I think means pid is only the id of child process.
So why can the parent process print?
How do the two processes run together?
// fork.c: create a new process
#include "kernel/types.h"
#include "user/user.h"
int
main()
{
int pid;
pid = fork();
printf("fork() returned %d\n", pid);
if(pid == 0){
printf("child\n");
} else {
printf("parent\n");
}
exit(0);
}
output:
ffoorrkk(()) rreettuurrnende d 0
1c9h
ilpda
rent
I focus my answer on showing how the observed output can result from the shown program. I think that it will already clear things up for you.
This is your output.
I edited it to use a good guess of what is parent (p) and child (c):
ffoorrkk(()) rreettuurrnende d 0\n
cpcpcpcpcpcpcpcpcpcpcpcpccpcpcppccc
1 c9h\n
pccpcpp
ilpda\n
ccpcpcc
rent
pppp
If you only use the chars with a "c" beneath, you get
fork() returned 0
child
If you only use the chars with a "p" beneath, you get
fork() returned 19
parent
Split that way, it should match what you know about how fork() works.
Comments already provided the actual answer to the three "?"-adorned questions in title and body of your question post.
Lundin:
It creates two processes and they are executed just as any other process, decided by the OS scheduler.
Yourself:
each time fork() is called it will return twice, the parent process will return the id of child process, and child process will return 0
Maybe for putting a more obvious point on it:
The parent process receives the child ID and also continues executing the program after the fork().
That is why the output occurs twice, similarily, interleaved, with differences in PID value and the selected if branch.
Relevant is also that in the given situation there is no line buffering. Otherwise there would be no character-by-character interleaving and everthing would be much more readable.
I'm trying to build a minishell and I've mostly everything but pipes working. I've read a lot of answers in this site and many others, but I'm not able to find my particular problem.
The sequence should end when the right-most process ends, this is: sleep 3 | sleep 3 | sleep 0 should immediately end, and not wait for any of the sleep 3 processes.
*argvv is a pointer to the first process (*argvv would be sleep 3, *(argvv + 1) is the next sleep 3, etc. I don't know what's going on, but something is wrong with file descriptors and everything breaks after a test.
For instance, when the input is sh> ls | wc | wc, the output is
sh> ls | wc | wc
sh> 1 3 25
, then it waits for some input. It's not until I press enter again it finishes. After that, sleep 3 does not work anymore.
Any help would be welcome, thanks a lot!
Edit:
Ok, I edited the code and everything seems to work fine, except sleep 3 | sleep 0 lasts 3 seconds, instead of immediately ending. I don't know how to fix this.
void execute(char ***argvv)
{
pid_t pid;
int pd[2];
int in = 0;
while (*argvv != NULL) {
pipe(pd);
if ((pid = fork()) < 0)
{
perror();
exit(1);
}
else if (pid == 0) {
dup2(in, 0);
if (*(argvv + 1) != NULL)
dup2(pf[1], 1);
close(pd[0]);
close(pd[1]);
execvp((*argvv)[0], *argvv);
perror();
exit(1);
}
else
{
close(pd[1]);
in = pd[0];
if (*(argvv + 1) == NULL)
close(pd[0]);
argvv++;
}
wait(&pid);
}
}
I think part of the problem may be in the use of wait(). It's pid parameter is an OUTPUT, reporting which fork()ed process ended. Every forked processed ends, and needs to be wait()ed for. When you run a second pipeline, all but one piece of the preceding pipeline is still ready to be wait()ed for.
Generally, you have several choices:
wait() in a loop until the process you want to end ends.
wait() in a loop until all the subprocesses end.
Use waitpid() to look for a particular process ending.
Arrange that only the last process in the chain is a child of your process, making the rest children of that. (This is done by some shell, though I don't remember which.) The problem with this is that it leaves extra children for the last process in the chain, which may confuse it.
Track all the child processes, and which have ended. When you background a pipeline, this allows you to display which parts of the pipeline are still running. (tcsh does this. bash does half.)
fork() twice for the earlier pipeline members, execvp() in the grandchild, then exit() in the child, and have the parent wait() for the child to finish before going on. This disconnects the grandchild from the parent, so it never needs to be waited for.
Do things involving ignoring SIGCHLD, but this will probably cause you a lot of grief, as it is all or nothing.
I have a piece of code and I have to explain what is happening in the exit.
while(wait(NULL)>0)
The code is the following:
#include <stdio.h>
main() {
int n=1;
while(n<5) {
n=n+1;
if (fork() == 0)
n=n+2;
}
printf("%d %d %d\n", getpid(), getppid(), n);
while (wait(NULL) > 0);
}
When I execute the program the result shows 6 processes with 6 children and respective parents, while the condition while n < 5 has been met. If we cancel
while (wait(NULL) > 0);
then some children remain as zombies.
For example, when you are in the first child the output should be n = 4 instead I get n = 5 and outputs the results randomly without order.
I want to understand exactly the behaviour of while (wait (NULL)> 0)
If the current process have no child processes, wait(NULL) returns -1. Otherwise it waits until one of them exits, and returns it's process ID.
So while wait(NULL) > 0); loops until there are no more child processes, since when the last child exits, wait() will return -1 and the while loop terminates. (And wait() returning 0 should be an impossible condition too).
For example, when you are in the first child the output should be n =
4
Look at the code again: the last time the thread enters the while, n<5, but then it increments n in the while body before exiting the while loop and printing.
(UPDATE: I just noticed that in your sample code, the line n=n+1 is not indented. Maybe this is just an accident in entering the code, but it may be contributing to your confusion, since "n=n+1" does not look like it's happening in the while loop) Obviously the compiler doesn't care, but from the wording of your question, it sounds as if you do not realize that after the n=n+2, any thread where n<5 will loop back and increment n at least one more time. This is why no thread ever outputs 4 or less for n.
I want to understand exactly the behaviour of while (wait (NULL)> 0)
This is may not be direct answer to your problem, which is more related to fork than while(wait(NULL)>0), but might help other people (like me, who found your post when searching about this construct)
tl;dr: it waits for termination of all (direct) childs.
wait(ptr) on success returns (non-negative) pid of terminated child, and saves its status to int pointed by ptr (you can safely pass NULL, if you don't care). On "fail", -1 is returned and errno set appropriately.
In case of this loop, we don't consider no child processes as error, contrarily: it would be error if it didn't happen.
For extra error handling, one could write:
while(wait(NULL) != -1);
if(errno != ECHILD) {
perror("wait() error");
exit(1)
}
How we can get this process with this condition??schema of process?
int main (int argc, char **argv) {
int i;
int pid;
for (i= 0; i < 3; i++) {
pid = fork();
if (pid < 0) break;// with this condition i dont understand??
}
while (wait(NULL) != -1);
fork() splits a process in two, and returns 0 (if this process is the child), or the PID of the child (if this process is the parent), or -1 if the fork failed. So, this line:
if (pid < 0) break;
Says "exit the loop if we failed to create a child process".
The diagram is a little confusing because of the way the processes (circles) correspond to the fork() calls in the loop. The three child processes of the main process are created when i is 0, 1, and 2 respectively (see the diagram at the bottom of this post).
Since the loop continues in both the parent and the child process from the point fork was called, this is how the forks happen:
i == 0: fork is called in the original parent. There are now two processes (the top one, and the left one).
i == 1: fork is called in the two existing processes. New children are the leftmost child on the second layer from the bottom, and the middle child on the third layer from the bottom. There are now four processes
i == 2: fork is called in all existing processes. New children are all remaining nodes (the bottom node, the two rightmost nodes in the second layer from the borrom, and the rightmost node in the third layer from the bottom)
i == 3: All 8 processes exit the loop
Here is the diagram again, with numbers indicating what the value of i was in the loop when the process was created:
-1 <--- this is the parent that starts the loop
/ | \
0 1 2
/ \ |
1 2 2
|
2
To understand your diagram you must rely on the behavior of fork: it splits the process in two, creating another process identical to the first (except for the PID) in a new memory location.
If you call it in a loop that's what happen:
When i=0 the first process will be split, creating another process that will start running from exactly this point on (so will skip the first loop). Focusing on the first process, it will continue the loop, generating another process when i=1. The second process, thus, will start from i=1, so will skip the first two loops. The first process will be split last time for i=2. The last copy created, however, will start running from i=2, so it will exit the loop and will not generate anything.
The first copy created will start the loop from i=1, generating two process, while the second copy will start from i=2, generating only one copy.
You can continue this reasoning and understand the rest of the diagram.
As others pointed out, if (pid < 0) is just a check to see if there are errors and does not modify the logic of the code.
fork returns -1 if the fork call failed. it returns the pid in parent and 0 in the child. The condition you're looking at doesn't really matter to the functioning of the code; it's just saying if there's an error with fork then exit the loop. If there's no error in the fork call then the process tree in your diagram will be built.
The reason why is that the same loop will continue running in the child processes. So the children will also continue to fork based on the value of i at the time fork was called.
fork return -1 on error, and 0 or positive else, so the line if (pid < 0) break; says "if there was error, exit from the loop".
Assuming that there is not error, it's something like:
At the beginning, i=0, and you have one process. let's call it p0.
In the line fork();, p0 creates another process. let's call it p1.
In everyone of them, we have i++ (so now i is 1), and we are iterating the loop again.
p0 and p1, separately, have a fork(); command, so everyone of them creates another process. let's call the new processes p2 and p3.
Now, in every process, we have i++, that set i to be 2, and we run the loop again.
Everyone of the 4 processes we have, run the line fork();, and creates a new process. so now we have also p4,p5,p6,p7.
Every process increase its i to 3, and then, since the loop condition is now false, the loop finally ends.
Now, the 8 process arrive (separately) to the next line.
(In fact, every iteration double the number of processes, so if you change the 3 to, for example, 15, you will have 2^15 processes at the end.)
I am trying to figure out the output for a block of C code using fork() and I am having some problems understanding why it comes out the way it does. I understand that when using fork() it starts another instance of the program in parallel and that the child instance will return 0. Could someone explain step by step the output to the block of code below? Thank you. EDIT: I FORGOT TO ADD THE EXIT(1) AFTER THE FOR LOOP. MY APOLOGIES.
main() { int status, i;
for (i=0; i<2; ++i){
printf("At the top of pass %d\n", i);
if (fork() == 0){
printf("this is a child, i=%d\n", i);
} else {
wait(&status);
printf("This is a parent, i=%d\n", i);
}
}
exit(1);
}
What happens on the first loop is that the first process forks. In one, fork() returns 0 and in the other it returns the pid of the child process So you'll get one that prints out "this is a child" and one that prints out "this is a parent". Both of those processes continue through the loop, incremement i to 1 and fork() again. Now you've got four processes: two children and two parents. All four processes will increment i to 2 and break out of the loop.
If you increased the loop termination condition to i<3 then the next time around the loop all four processes will execute fork() and you'd have eight processes in total. If there was no limit in the loop, you'd have a fork bomb where you'd just exponentially create more and more processes each loop until the system runs out of resources.
This code can be tricky to explain. The reason why is that the first child does not exit and will itself call fork. Try modifying the code to include the process id on each print line such as:
printf("At the top of pass %d in pid %u\n", i, getpid());
Then notice how the child becomes the parent...