Code:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
int foo(const char *whoami)
{
printf("I am a %s. My pid is:%d my ppid is %d\n",
whoami, getpid(), getppid() );
return 1;
}
int main(void)
{
int n= 10;
int i=0;
int status=0;
int x = 5;
printf("Creating %d children\n", n);
foo("parent");
for(i=0;i<n;i++)
{
pid_t pid=fork();
if (pid==0) /* only execute this if child */
{
foo("child");
for(i=0; i< 5; i++);
{
x++;
printf("x value in for: %d ", x);
}
exit(0);
}
wait(&status); /* only the parent waits */
}
x = 100 * x;
printf("x value in main: %d ", x);
return 0;
}
The output is
Creating 10 children
I am a parent. My pid is:7208 my ppid is 6223
I am a child. My pid is:7209 my ppid is 7208
x value in for: 6 I am a child. My pid is:7210 my ppid is 7208
x value in for: 6 I am a child. My pid is:7211 my ppid is 7208
x value in for: 6 I am a child. My pid is:7212 my ppid is 7208
x value in for: 6 I am a child. My pid is:7213 my ppid is 7208
x value in for: 6 I am a child. My pid is:7214 my ppid is 7208
x value in for: 6 I am a child. My pid is:7215 my ppid is 7208
x value in for: 6 I am a child. My pid is:7216 my ppid is 7208
x value in for: 6 I am a child. My pid is:7217 my ppid is 7208
x value in for: 6 I am a child. My pid is:7218 my ppid is 7208
x value in for: 6 x value in main: 500
Since I'm very pretty new forking I try to understand the logic..The point that I didnt understand quite yet is why the for loop in children process turns 1 time.. How do I make it 5 times?
As far as I understand that parent and children code parts executes parallel, but what if I want to do a recursion in children processes, is that possible? Thanks for all your attention..
Best
edit: typo