您如何从共享内存中分离一系列字符串?C



我有:

int array_id;
char* records[10];
// get the shared segment
if ((array_id = shmget(IPC_PRIVATE, 1, 0666)) == -1) {
            perror("Array Creating");
}
// attach
records[0] = (char*) shmat(array_id, (void*)0, 0);
if ((int) *records == -1) {
     perror("Array Attachment");
}

哪个工作正常,但是当我尝试分离时,我会得到"无效的参数"错误。

// detach
int error;
if( (error = shmdt((void*) records[0])) == -1) {
      perror(array detachment);   
}

有什么想法吗?谢谢

shmdt()中,无需将指针参数转换为 void*,它将自动照顾它。

shmdt((void*) records[0]))删除(void*)。应该这样。

if ((error = shmdt(records[0]) ) == -1)
{
  perror("Array detachment");
}

它将起作用。

shmat()中,错误时,它会返回(void*) -1,因此您的比较将发出警告。所以喜欢这个

if ((char *)records[0] == (void *)-1)
{
  perror("Array Attachment");
}

假设附件进行得很好,invalid argument只是意味着该段已经已分离,或者records[0]的值以来已通过附加设置以来已更改。

最新更新