0

This is my program:

int  a;
int main(void)
{

a=10;
//declare and create 2 pipes
int p1[2], p2[2];
pipe(p1);
pipe(p2);
int ra;
for(int i=0;i<3;i++)
{   
   pid=fork();
   if(pid==0) 
   {
      close(p1[1]);
      close(p2[0]);
      read(p1[0],&ra,3);

      while(ra>0)
      {

        ra-=1;
        printf("%i a are available, reported by process %i\n",ra,getpid());
        close(p1[0]);
        write(p2[1],&ra,3);

        close(p2[1]);

      }
      break;

   }
   else
   if(pid>0)
   {


   }else
   {
       wait(NULL);

   }

 }
 }

if(pid>0)    //parent process outside for loop
{
    close(p1[0]);
    close(p2[1]);
    if(a>0)
    {
        write(p1[1],&a,3);
        close(p1[1]);
    }
    else
        exit(0);
    read(p2[0],&ra,3);
    a=ra;
    close(p2[0]);

 }

What it does is creating 6 child processes from parent process, then assigning them to access the global variable a and decreasing it 1. These processes communicate with their parent process via two pipes. Parent process will write the value to the pipe 1. Child processes will read it from pipe 1, print it out and write it back to the pipe 2 after decreasing it 1. Finally, parent process will read the value from pipe 2 and check if the value > 0 to decide to stop the program or not.

I expect the following result:

35 seats are available, reported by process 1
34 seats are available, reported by process 2
33 seats are available, reported by process 5
32 seats are available, reported by process 0
31 seats are available, reported by process 2
....
1 seats are available, reported by process 3
0 seats are available, reported by process 1

but the actual output is:

35 seats are available, reported by process 2
34 seats are available, reported by process 2
33 seats are available, reported by process 2
32 seats are available, reported by process 2
31 seats are available, reported by process 2
....
1 seats are available, reported by process 2
0 seats are available, reported by process 2

Question: I dont know how to force other child processes running alternatively (or randomly) so the result would be like the first one above. Please help me.

4

1 回答 1

1

如果您关心工作完成的顺序,则必须编写代码来强制执行特定的顺序。否则,实现可以自由选择最有效的顺序。您可以使用互斥体、信号量、管道、文件或任何其他您喜欢的同步机制——但您必须实际操作。它不会自己发生。

wait如果fork返回错误,为什么要调用?

于 2013-10-15T10:25:23.933 回答