2009-02-28 12 views
0

すべての変数が以前に宣言されていると仮定します。子プロセスは、それが実行されていないと思うものを印刷しません。親プロセスは正常に動作しますが、共有メモリは取得されません。 私はCの標準出力ストリームは、内部でデータをバッファリングここで子プロセスが何も印刷しないのはなぜですか?

// create 5 child process 
for(int k=0;k<5;k++){ 

    // fork a child process 
    pid = fork(); 

    // error occured on fork 
    if (pid < 0) { 
     fprintf(stderr, "Fork Failed"); 
     return 1; 
    } 
    // this is what the child process will run 
    else if (pid == 0) { 
     //create a shared mem segment 
     segment_id = shmget(IPC_PRIVATE, size, S_IRUSR | S_IWUSR); 

     //attach the shared memory segment 
     shared_memory = (char *) shmat(segment_id, NULL, 0); 

     printf("this is child"); 

     double x = 0; 
     double sum = 0; 

     // Run process that sums the function 
     for(int i=0; i<n; i++){ 
      // get random number in range of x1-x2 
      x = rand()%(x2 - x1 + 1) + x1; 
      sum = sum + f(x); 
     } 

     //write output to the shared memory segment 
     sprintf(shared_memory, "%f", sum); 
     execlp("/bin/ls", "ls", NULL); 

    } 

    // this is what the parent process will run 
    else { 

     //print output from shared memory 
     printf("\n*%s", shared_memory); 

     //detach shared memory 
     shmdt(shared_memory); 

     //Here we add the shared memory to the array 
     // To add together at the end 
     // but since I cant get the memory to share 
     // the array can't be implemented 

     //remove the shared memory segment 
     shmctl(segment_id, IPC_RMID, NULL); 

     wait(NULL); 
    } 
} // End of for statement 
+0

shm *操作のエラー状態はチェックしていません。 –

答えて

10

...このコードの長さをお詫び申し上げます。あなたの "this is child"メッセージがバッファされている可能性があり、バッファがexeclpによってフラッシュされていないので、バッファは消えます。 fflush(stdout)を試してください。 printfの後に。ちなみに、fork()の前にこれを行う必要があります。そのため、子と親の両方がフォークの前にバッファリングされた出力を書き込もうとしません。

+0

印刷出力に改行が含まれていないため、おそらく問題になる可能性があります。出力が行バッファーされていた場合、改行はデータを強制的に表示します。 –

+0

また、これはstderrに診断を出力するのに適しています。バッファリングされておらず、簡単に失われることはありません。 –

+0

私はこれを試みたが、それは私のために働いていない。私は 'fflush(stdout);'を使用しましたが、まだ子プロセスは何も印刷していません。 「現在実行中のもの(現在、プロセッサーが子プロセスか親プロセスかによって提供されているもの)は、現在、 – Merom

-1

まず、すべての共有メモリを取り除き、子プロセスがprintfを正常に実行できるかどうかを確認します。

スニペットの外観では、子プロセスでshared_memoryを初期化していますが、親プロセスでは初期化していません。

3

標準エラー出力時にバッファリングされません。

fprintf(stderr,"Plop\n"); 

はまた、共有メモリのもの(segment_idに、SHARED_MEMORY)は、親に初期化されていない(または、それがある場合、それは子供と同じではありません)。

さらに、子プロセスの実行中に親プロセスが共有メモリを破壊する可能性があります。親は最初に待ってから、子が生成したデータを処理する必要があります。

関連する問題