【问题标题】:How to grab data from a shared memory segment?如何从共享内存段中获取数据?
【发布时间】:2013-05-05 22:01:40
【问题描述】:

这是我服务器的代码:

#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)。

如何从共享内存段中读取一些客户端写入的数据?

【问题讨论】:

  • 为什么在你的案例中使用共享内存?你不能只使用先进先出吗?

标签: c linux process shared-memory


【解决方案1】:

我实际上建议您使用 Posix 共享内存,请参阅 shm_overview(7) 而不是旧的(几乎过时的)System V 共享内存。

如果您想坚持使用shmget(即旧的 System V IPC,请参阅svipc(7)..),您需要致电shmat(2)

所以您可能希望在成功调用shmat 后访问您的data。您确实对data 的类型和大小有一些约定。您 cpuld 在某个标头中定义了一个 struct my_shared_data_st(由客户端和服务器使用),然后您投射 (struct my_shared_data_st*)data 来访问它。

您在服务器和客户端进程中都需要shmgetshmat

使用共享内存,您需要某种方式在客户端和服务器之间进行同步(即告诉消费者部分生产者端完成了该数据的生成)。

阅读 advanced linux programming 并阅读几遍手册页。

【讨论】:

  • 只需将其解析为pid_t ?铸造?
  • 你为什么说pid_t?您共享的数据类型是什么?你如何同步?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-05
  • 1970-01-01
  • 1970-01-01
  • 2015-06-01
  • 2023-03-14
  • 1970-01-01
相关资源
最近更新 更多