如何使子进程访问并交替更改相同的值

时间:2013-10-15 10:20:41

标签: c multiprocessing fork pipe

这是我的计划:

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]);

 }

它的作用是从父进程创建6个子进程,然后分配它们以访问全局变量a并减少它1.这些进程通过两个管道与其父进程通信。父进程将值写入管道1.子进程将从管道1读取它,打印出来并在减少它后将其写回管道2.最后,父进程将从管道2读取值并检查是否值&gt; 0决定是否停止该程序。

我希望得到以下结果:

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

但实际输出是:

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

问题:我不知道如何强制其他子进程交替(或随机)运行,因此结果就像上面的第一个。 请帮帮我。

1 个答案:

答案 0 :(得分:1)

如果您关心完成工作的顺序,则必须编写代码来强制执行特定的排序。否则,实施可以自由选择最有效的订单。您可以使用互斥锁,sempahore,管道,文件或任何其他您喜欢的同步机制 - 但您必须实际执行此操作。它本身不会发生。

如果wait返回错误,为什么要致电fork