Wednesday, May 16, 2012

Synchronizing Parent & Child process

I want to synchronize the parent and child process to alternatively print 1 to 10 into a file. And output which process printed the number. The following code prints alternatively, but the same number. Please help me out!



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

#define MSGSIZE 16
int parent= 1;
int n=-1;
main ()
{
int i;
char *msg = "How are you?";
char inbuff[MSGSIZE];
int p=0;
FILE *fp1,*fp2;
pid_t ret;

ret = fork ();
if (ret > 0)
{
i = 0;
while (i < 10)
{

n++;
// sprintf(msg, "%d", n);
// fp=fopen("abc.txt","a");
// write (p[1], itoa(n,msg,MSGSIZE), MSGSIZE);
// sleep (2);
// fclose(fp);
//read (p[0], inbuff, MSGSIZE);

fp1=fopen("abc.txt","r");
fscanf(fp1,"%d",&n);
fclose(fp1);
fp1=fopen("abc.txt","w");
fprintf(fp1,"%d",n);
printf("Parent: %d\n", n);
i++;
fclose(fp1);
sleep(2);

}
exit(1);
}
else
{
i = 0;
while (i < 10)
{

n++;
//sleep (1);
// read (p[0], inbuff, MSGSIZE);

fp2=fopen("abc.txt","r");
fscanf(fp2,"%d",&n);
fclose(fp2);
fp2=fopen("abc.txt","w");

fprintf(fp2,"%d",n);
printf("Child: %d\n", n);
i++;

sleep(2);

}
}
exit (0);
}




No comments:

Post a Comment