0

これは私のプログラムです:

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 つの子プロセスを作成し、それらをグローバル変数にアクセスするように割り当て、それをa1 減らします。これらのプロセスは、2 つのパイプを介して親プロセスと通信します。親プロセスはパイプ 1 に値を書き込みます。子プロセスはパイプ 1 から値を読み取り、それを出力して、パイプ 1 を減らした後にパイプ 2 に書き戻します。最後に、親プロセスはパイプ 2 から値を読み取り、プログラムを停止するかどうかを決定する値 > 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

質問:他の子プロセスを交互に (またはランダムに) 強制的に実行する方法がわからないため、結果は上記の最初のもののようになります。私を助けてください。

4

1 に答える 1

1

作業の順序が気になる場合は、特定の順序を強制するコードを作成する必要があります。それ以外の場合、実装は最も効率的な順序を自由に選択できます。ミューテックス、センパフォア、パイプ、ファイル、またはその他の任意の同期メカニズムを使用できますが、実際に実行する必要があります。それはそれ自体では起こりません。

なぜエラーを返すwait場合に呼び出すのですか?fork

于 2013-10-15T10:25:23.933 に答える