Reputation: 19
I am trying to run the following code on my Ubuntu machine
#include <pthread.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
fork();
fork();
fork();
printf("hello\n");
exit(0);
}
When I run above codes with calling fork() two times, I get four "Hello"s as expected. However, when I run the above code, the program just loops and never returns.(it does print two "Hello"s, by the way)
Why is this happening and how can I fix this?
My thanks in advance.
Upvotes: 1
Views: 242
Reputation: 25
I modified your code a bit by including pid
to it, just to print what is happening. Take this execute in your system and you'll be able to figure out.
After three fork "hello" should be printed 8 times (I think by mistake you mentioned two times in your question).
#include <pthread.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
pid_t pid1,pid2,pid3;
pid1 = fork();
pid2 = fork();
pid3 = fork();
printf("hello in [%u][%u][%u]\n",pid1,pid2,pid3);
exit(0);
}
Out put which I get is as follows:
[p@devmach PROG]$ ./a.out
hello in [30092][30093][30094]
[p@devmach PROG]$ hello in [30092][30093][0]
hello in [30092][0][30095]
hello in [0][30096][30097]
hello in [30092][0][0]
hello in [0][30096][0]
hello in [0][0][30098]
hello in [0][0][0]
Upvotes: 2