Reputation: 947
I have recently started learning how to program in C under Linux and have written the following code to create some processes:
void generate()
{
int pid;
for(int i=1;i<=10;i++)
{
pid = fork();
}
if (pid<0)
{
printf("Error Fork");
exit(1);
}
if(pid == 0)
{
printf("Fiu pid: %d --- Parinte pid: %d\n", getpid(), getppid());
//count ++;
}
if(pid > 0 )
{
printf("Parinte pid: %d\n", getpid());
//count++;
wait();
}
}
The question is: how should i declare/increment the count variable in order to print the total number of processes the function has created?
Upvotes: 0
Views: 1367
Reputation: 528
Probably there are better approaches but.. You can append a new line/character to a temp file every time a child is created. Then you just have to count the lines/characters of the file.
Upvotes: 0
Reputation: 27572
It's simple. Fork
produces a child for each parent. The answer is therefore 2^10 or 1024.
Put a printf
after the fork
and comment out the other extraneous output. Run as
./a.out | sort | uniq | wc
The output is is 1024.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
void generate()
{
int pid;
for(int i=1;i<=10;i++)
{
pid = fork();
printf("%d\n", getpid());
}
if (pid<0)
{
//printf("Error Fork");
exit(1);
}
if(pid == 0)
{
//printf("Fiu pid: %d --- Parinte pid: %d\n", getpid(), getppid());
//count ++;
}
if(pid > 0 )
{
//printf("Parinte pid: %d\n", getpid());
//count++;
wait(NULL);
}
}
int main(int argc, char *argv[])
{
generate();
return(0);
}
Upvotes: 2