Reputation: 33
I am writing a C program that uses a fork command and loops 10 times, at the same time, the process ID will be displayed in each loop.
Following are my codes:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
main ()
{ int x;
for(x=0;x<10;x++)
{
fork();
printf("The process ID (PID): %d \n",getpid());
}
}
My codes generate numerous of process ID,is there anything wrong in the program?
Upvotes: 3
Views: 4933
Reputation: 1363
fork()
system call creates a child which executes the same code as the parent. From that moment, there are 2 processes executing the next line: parent and child. Each of them executes the printf()
.
The second time the for
loop is executed, it is executed by the parent and the child: each of them execute fork()
, and so from that moment there are 4 processes: the 2 first ones, and their new children.
So, for every iteration in the loop you are doubling the number of processes. The total number of processes is thus 2^10 = 1024.
So, the printf()
inside the for
loop is executed:
Total: 10*2 + 9*2 + 8*4 + 7*8 + 6*16 + 5*32 + 4*64 + 3*128 + 2*256 + 1*512 = 2046.
The printf()
is executed 2046 times.
Upvotes: 7
Reputation: 546
check my exemple
pid_t pID = fork();
if (pID == 0) // child
{
// Code only executed by child process
sIdentifier = "Child Process: ";
globalVariable++;
iStackVariable++;
}
else if (pID < 0) // failed to fork
{
cerr << "Failed to fork" << endl;
exit(1);
// Throw exception
}
else // parent
{
// Code only executed by parent process
sIdentifier = "Parent Process:";
}
// Code executed by both parent and child.
Upvotes: 0