0

すべての変数が以前に宣言されていると仮定します...宣言されているためです。子プロセスは、実行されていないと思わせるものを何も出力しません。共有メモリを取得しませんが、親プロセスは正常に実行されます。このコードが長くて申し訳ありません...

// 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
4

3 に答える 3

12

C stdout ストリームは、データを内部的にバッファリングします。「これは子です」というメッセージがバッファリングされている可能性があり、バッファは execlp によってフラッシュされていないため、消えてしまいます。fflush(stdout);printf の後にa を試してください。ちなみに、fork()子と親の両方がフォークの前からバッファリングされた出力を書き込もうとしないように、これも前に行う必要があります。

于 2009-02-28T01:35:22.163 に答える
3

バッファリングされていない stderr に出力します。

fprintf(stderr,"Plop\n");

また、共有メモリの要素 (segment_id、shared_memory) は親で初期化されません (または、初期化されている場合は子と同じではありません)。

さらに、子がまだ処理している間に、親が共有メモリのものを破壊する可能性があります。親は最初に待機してから、子によって生成されたデータを処理する必要があります。

于 2009-02-28T01:50:02.767 に答える
-1

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

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

于 2009-02-28T01:38:10.817 に答える