1

これは私のサーバーのコードです:

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/fcntl.h>

#define FIFONAME "fifo_clientTOserver"
#define SHM_SIZE 1024  /* make it a 1K shared memory segment */


int main(int argc, char *argv[])
{

    // create a FIFO named pipe - only if it's not already exists
    if(mkfifo(FIFONAME , 0666) < 0)
    {
        printf("Unable to create a fifo");
        exit(-1);
    }



    /* make the key: */

    key_t key;

    if ((key = ftok("shmdemo.c", 'j')) == -1) {
        perror("ftok");
        exit(1);
    }


    else /* This is not needed, just for success message*/
    {
       printf("ftok success\n");
    }


    // create the shared memory

    int shmid = shmget(key, sizeof(int), S_IRUSR | S_IWUSR | IPC_CREAT);

    if ( 0 > shmid )
    {
        perror("shmget"); /*Displays the error message*/
    }

    else /* This is not needed, just for success message*/
    {
       printf("shmget success!\n");
    }


    // pointer to the shared memory
    char *data = shmat(shmid, NULL, 0);

    /* attach to the segment to get a pointer to it: */
    if (data == (char *)(-1))
    {
        perror("shmat");
        exit(1);
    }


    /**
     *  How to signal to a process :
     *  kill(pid, SIGUSR1);
     */


    return 0;

}

私のサーバーは、共有メモリ セグメント 、 process-id (type ) から読み取る必要がありますpid_t

一部のクライアントが書き込んだデータを共有メモリセグメントから読み取るにはどうすればよいですか?

4

1 に答える 1

2

実際には、Posix 共有メモリを使用することをお勧めします。古い (そしてほとんど廃止された) System V 共有メモリの代わりに、shm_overview(7)を参照してください。

shmget(古い System V IPC など、svipc(7)を参照)に固執したい場合は、 shmat(2)を呼び出す必要があります。

したがって、呼び出しdataが成功した後にアクセスしたいと思うでしょう。shmatそのタイプとサイズについては、いくつかの規則がありdataます。struct my_shared_data_stいくつかのヘッダー(クライアントとサーバーの両方で使用される)で定義されていることを確認してから、それにアクセスするためにキャストし(struct my_shared_data_st*)dataます。

サーバー プロセスとクライアント プロセスの両方shmgetで との両方が必要です。shmat

共有メモリでは、クライアントとサーバー間で同期する何らかの方法が必要です (つまり、プロデューサー側がそのデータの生成を終了したことをコンシューマー側に伝えるため)。

高度な Linux プログラミングを読み、man ページを数回読んでください。

于 2013-05-11T09:03:24.490 に答える