2013-05-11 42 views
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; 

} 

我的服務器需要從共享內存段,進程ID(類型pid_t)來讀取。

如何從共享內存段讀取某些客戶端寫入的數據?

+0

爲什麼你在你的情況下使用共享內存?你不能只用fifo嗎? – 2013-05-11 09:16:36

回答

2

我實際上會建議你使用Posix共享內存,請參閱shm_overview(7),而不是舊的(幾乎過時的)System V共享內存。

如果你要堅持shmget(即舊系統V IPC,見svipc(7) ..),你需要調用shmat(2)

所以你可能要訪問你的成功shmat呼叫data後。你確實有一些關於data的類型和大小的約定。您在某個頭文件中定義了一個struct my_shared_data_st(由客戶端和服務器使用),然後您投(struct my_shared_data_st*)data來訪問它。

您在服務器和客戶端進程中都需要shmgetshmat

對於共享內存,您需要某種方式來在客戶端和服務器之間進行同步(即告訴消費者部分生產者完成生產該數據)。

閱讀advanced linux programming並閱讀好幾次手冊頁。

+0

只是將它解析爲'pid_t'?鑄造? – ron 2013-05-11 09:06:26

+0

你爲什麼要說'pid_t'?你分享的數據的類型是什麼?你如何同步? – 2013-05-11 09:09:37