【问题标题】:Incorrect interprocess reading进程间读取不正确
【发布时间】:2015-12-01 19:49:09
【问题描述】:

我正在做一个带有共享内存的客户端/服务器通信系统。我正在与客户端一起编写服务器将读取的 PID。问题是当我尝试读取该值时,它只读取最不重要的 8 位。这是一段代码:

 int receive(void* data, void * connection) {
   connection_t * c = (connection_t *)connection;

   printf("PRINTING: %d \n", *(c->address));


   return 0;
}

void notify_server() {
  int mem_id = shmget(PUBLIC_KEY, PAGE_SIZE, PERMISSION_FLAGS);
  int * address = shmat(mem_id, NULL, 0);
  int sem_id = semget(PUBLIC_KEY, 1, PERMISSION_FLAGS);

  *address = (pid_t)PRIVATE_KEY;
  printf("FROM CLIENT, PRINT MY PID --- %d\n", *address);
}

结构是:

typedef struct {
  int id;
  char * address;
  struct shmid_ds data;
  int sem_id;
  struct sembuf sb;
} connection_t;

【问题讨论】:

    标签: linux process server client communication


    【解决方案1】:

    address 字段是char:char * address;

    所以*(c->address) 当然会给出一个char,它是 8 位。

    【讨论】:

    • 解决方法是在解引用指针之前将地址强制转换为 (int *)。
    • 为什么不在结构中声明为int?
    • 因为一般情况下共享内存中的数据都会被当作字符串处理,这是一个例外。
    猜你喜欢
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    • 2021-12-19
    • 1970-01-01
    • 2011-03-11
    相关资源
    最近更新 更多