0

I have a algorithm to create a N-processes using fork(). Processes are generating successfully because I drew them by hand.

The problem is when I try to print them (not needed as a tree) I find duplicated processes in output. Cant find why.

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>

void GenerateTree(int n){
    printf("PID: %d | PPID: %d\n",getpid(),getppid());

    int *ptr = mmap(NULL,n*sizeof(int),PROT_READ | PROT_WRITE,MAP_SHARED | MAP_ANONYMOUS,0,0); 
    int *ptr1 = mmap(NULL,sizeof(int),PROT_READ | PROT_WRITE,MAP_SHARED | MAP_ANONYMOUS,0,0);
    ptr1[0]=0;
    int z = 0;
    while(z<n){
        if(ptr1[0]<n-1){
            pid_t pid;        
            pid = fork();
            if(pid==0){
                printf("PID: %d | PPID: %d\n",getpid(),getppid());
                ptr[ptr1[0]] = getpid();
                z++;
                ptr1[0]=ptr1[0]+1;
                if(ptr1[0]<n-1){
                    fork();    
                    printf("PID: %d | PPID: %d\n",getpid(),getppid());                  
                    ptr[ptr1[0]] = getpid();
                    ptr1[0]=ptr1[0]+1;                    
                    z++;              
                }
                else{                    
                    break;
                }
            }
            else{
                wait(NULL);
                break;
            }
        }
        else{
            break;
        }
    }
}    

int main(int argc, char const *argv[])
{
    GenerateTree(11);
    return 0;
} 

And the output looks like this.

PID: 5480 | PPID: 1168
PID: 5481 | PPID: 5480
PID: 5481 | PPID: 5480
PID: 5482 | PPID: 5481
PID: 5483 | PPID: 5481
PID: 5484 | PPID: 5482  
PID: 5483 | PPID: 5481 
PID: 5484 | PPID: 5482
PID: 5486 | PPID: 5484
PID: 5485 | PPID: 5483
PID: 5487 | PPID: 5483
PID: 5488 | PPID: 5484
PID: 5489 | PPID: 5485
PID: 5490 | PPID: 5486

Thanks for your help!

Ðаn
  • 10,934
  • 11
  • 59
  • 95
myge32
  • 75
  • 8
  • How are you running the program? Are you reflecting the output to a file or piping it to another program? – Jonathan Leffler Mar 31 '21 at 02:47
  • Oh flip — the spell mangler on my iPhone changed 'redirected' to 'reflected' and I didn't notice; sorry! Your problem is well described in [`printf()` anomaly after `fork()`](https://stackoverflow.com/q/2530663/15168). Without the redirection, you would not see the duplicated information. Because of the redirection, standard output is fully buffered, not line buffered as usual, and the duplication occurs. – Jonathan Leffler Mar 31 '21 at 04:04

0 Answers0