Hello!
So, I have a problem with the following code... I'd like to know, why the variables pid and ppid are not initialized? Inside the if scope, if I print them out, they are initialized to getpid() and getppid() value, but when I want to print them out in else scope of if block, they are zero. So now I am wondering, why the value is not being keept?
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
void vzporedno()
{
int i, j;
for ( i = 0; i < 3; i++ )
{
int ret = fork();
if ( ret == 0 )
{
printf("PID: %d, PPID: %d\n", (int)getpid(), (int)getppid());
exit(0);
}
}
for ( j = 0; j < 3; j++ )
wait(0);
}
void zaporedno()
{
int i;
for ( i = 0; i < 1; i++ )
{
int ret = fork();
if ( ret == 0 )
{
printf("PID: %d, PPID: %d\n", (int)getpid(), (int)getppid());
exit(0);
}
else
wait(0);
}
}
int main(int argc, char** argv)
{
int i, j, k, check = 0;
int pid=0, ppid=0;
for ( i = 0; i < 3; i++ )
{
int ret = fork();
if ( ret == 0 )
{
if ( check < 2 )
{
zaporedno();
pid = (int)getpid(); int ppid = (int)getppid();
exit(0);
}
else
{
vzporedno();
printf("PID: %d, PPID:%d\n", pid, ppid);
printf("PID: %d, PPID:%d\n", (int)getpid(), (int)getppid());
exit(0);
}
}
else
wait(0);
check++;
}
for ( k = 0; k < 2; k++ ){
wait(0);
}
printf("PID: %d, PPID:%d\n", (int)getpid(), (int)getppid());
return 0;
}