1

Linux 2.6を使用していますが、奇妙な問題があります。プロセスごとに1つずつ、3つの異なる共有メモリセグメントを取得する必要がある3つの並行プロセス(同じプロセスからフォークされた)があります。各プロセスはこのコードを実行します(「メッセージ」タイプはユーザー定義であることに注意してください)

    message *m;
    int fd = shm_open("message", O_CREAT|O_RDWR, S_IRUSR|S_IWUSR);
    ftruncate(fd, sizeof(message));
    m = mmap(NULL, sizeof(message), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
    char messagename[16];
    snprintf(messagename, sizeof(messagename), "%p", m);
    char path[32] = "/dev/shm/";
    strcat(path, messagename);
    rename("/dev/shm/message", path);

少し説明させてください。すべてのプロセスに、メッセージを含む共有メモリゾーンを割り当ててもらいたいのです。別のプロセス(メッセージ受信者)が同じshmにアクセスできるようにするために、shmファイルの名前を「message」からメッセージポインターにちなんで名付けられた文字列に変更します(これは、メッセージを受信するプロセスが既にポインターを知っているためです)。

しかし、プログラムを実行するときに、shm_openで取得したfdをmmapするときにすべてのプロセスが受け取ったポインターを(デバッグ目的で)出力しようとしましたが、すべてのプロセスが同じポインターを持っていることに気付きました。どうしてそれは可能ですか?他のプロセスが最初のプロセスの後でセグメントの名前を変更する前にshm_open()を実行したのではないかと思ったので、プロセス共有ミューテックスを使用してこれらのコード行をアトミック操作にしようとしましたが、問題は解決しません。

どんな種類の助けや提案も本当にありがたいです。

4

3 に答える 3

2

Your processes all started with identical address space layouts at the moment of forking, and then followed very similar code paths. It is therefore not surprising that they all end up with the same value of m.

However, once they became separate processes, their address spaces became independent, so having the same value of m does not imply that all of the ms are pointing to the same thing.

Furthermore, I am not sure that your idea of renaming the /dev/shm entry after creating the shared memory block is safe or portable. If you want each process's shared memory block to have a unique name, why not base the name on the process ID (which is guaranteed to be unique at a given point in time) and pass it directly to shm_open, rather than going to the bother of renaming it afterwards?

于 2011-02-23T12:19:47.573 に答える
1

The same virtual address in different processes can (and usually does) map to different physical pages in memory. You might want to read the wikipedia article on virtual memory.

于 2011-02-23T12:19:18.780 に答える
0

I solved a similar problem simply by making the mmap before forking. So after forking the same area is shared between all processes. I then put my semaphores and mutexes on defined positions. It works perfectly.

于 2011-02-23T18:24:43.510 に答える