Synchronize parent and forked process using POSIX named semaphores to print in text file

34 Views Asked by At

I want to print numbers from 1 to 99 in a text file where:

  • parent process prints odd numbers.
  • child process prints even numbers. Here is what I've tried:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
#include<semaphore.h>
#include<sys/types.h>
#include<fcntl.h>
FILE * ptr;     //file pointer

sem_t *sem_even,*sem_odd; //semaphores

void fileWR();  

int main(void){

sem_even=sem_open("/S_even",O_CREAT,0644,0); //initiliaze sem _even to 0
sem_odd=sem_open("/S_odd",O_CREAT,0644,1); //initialize se_odd to 1

fileWR();
return 0;
        }

fileWR function:




void fileWR(){

    ptr=fopen("./TpSemaphore.txt","w+"); //open file in read write mode
    
    if(ptr==NULL){
        fprintf(stderr,"ERROR!");
        exit(-1);
            }
    if(fork()!=0){
        //Parent processs
        puts("#### Parent #################");
        int i=1;
        
        while(i<100){
                    
        if(i%2==0) {  //Critical section
        
            sem_wait(sem_odd);
            //print in file
            fprintf(ptr,"%d ",i);
            //visualize which value is being printed
            printf("%d ",i);
            
            sem_post(sem_even);
                    }
            i++;    
            
        }
        sem_unlink("S_odd"); //unlink semphore
        sem_close(sem_odd); //close semaphore
        fclose(ptr);    //close file
        exit(0);
    }
    else{
        //Child process
    
        puts("#### Child #################");
        int j=1;
        while(j<100){
            
        if(j%2!=0) {
            sem_wait(sem_even);
            //print in file
            fprintf(ptr,"%d ",j);
            
            printf("%d ",j);
            
            sem_post(sem_odd);
                        }
            j++;    
        }
        
        sem_unlink("S_even");
        sem_close(sem_even);
        fclose(ptr);
        exit(0);
    }

}

Output expected 1 2 3 4 5 6 7 8 9 10 .... etc

But all what i get is undefined behavior

What i'm missing ? do i need to use shared memory ? Please, what's the right way to implement posix semaphores in IPC.

0

There are 0 best solutions below