Perror C++
why isn’t my array saving in c?
i’m trying to print the children of a process backwards, but once i exit the for loop the children are getting printed as 0
for(i = 0; i < counter; i++)
{
switch(pid = fork())
{
case -1:
perror("Could not forkn");
exit(1);
case 0:
reverse[arrayCount] = getpid();
arrayCount++;
exit(0);
/*parent*/
default:
wait(NULL);
}
}
int count;
for(count = depth; count >= 0; count–)
{
printf(“child: %dn”, reverse[count]);
}
Because a child process inherits parent’s data values before a fork is called, we will print the reversed array in the deepest child.
Try this, I am not sure it works though.
const int MAXDEPTH = 10; // Change this to a desirable value
pid_t PidArray [MAXDEPTH + 1];
int Level = 0;
int main (void)
{
PidArray [Level++] = getpid ();
if (Level < MAXDEPTH)
{
if (fork() < 0)
{
perror("Could not fork at level %dn", MyLevel);
exit(1);
}
}
else
{
// Print the reserved array at end of the chain
// That is the deepest child will print this
for (int count = MAXDEPTH; count >= 0; count–)
{
printf (“child: %dn”, PidArray [count]);
}
wait(NULL);
}
exit (0);
}
Good luck !
