I'm working on a little project here and one of the parts requires me to do something if a flag is on and other thing is the flag is off concurrently (using fork()). Althought I know this could bring mutex problems, I cannot seem to get it working. I don't think I ever get mutex anyway.
A piece of my code looks like this:
int i=0;
pid_t pid;
char c[1];
for(i=0;i<len;i++)
{
pid=fork();
if(pid)
{
wait(&w);
}
else
{
read(fd,&c,1);
printf("I'm son %d, read: %s, pos value: %d\n",getpid(),c,pos);
if(pos==0)
{
printf("I'm son %d, writing out in out1.txt\n",getpid());
//some writing instructions...
pos=1;
}
else
{
printf("I'm son %d, writing out in out2.txt\n",getpid());
//some writing instructions...
pos=0;
}
exit(0);
}
}
The problem is that I'm always getting in the same if, thus, I always write only in one of the files and I need to alternate the writing between two files.
Actual output:
I'm son <NUMBER>, writing out in out1.txt
I'm son <NUMBER>, writing out in out1.txt
I'm son <NUMBER>, writing out in out1.txt
I'm son <NUMBER>, writing out in out1.txt
I'm son <NUMBER>, writing out in out1.txt
Desired output:
I'm son <NUMBER>, writing out in out1.txt
I'm son <NUMBER>, writing out in out2.txt
I'm son <NUMBER>, writing out in out1.txt
I'm son <NUMBER>, writing out in out2.txt
I'm son <NUMBER>, writing out in out1.txt
Thanks!
Aucun commentaire:
Enregistrer un commentaire