gpt4 book ai didi

c - 将字符串存储在共享内存 C 上

转载 作者:行者123 更新时间:2023-11-30 16:55:46 25 4
gpt4 key购买 nike

您好,这段代码在共享内存整数上存储工作正常,但我想存储字符串,我如何修改它来做到这一点?
例如,输出将是 Written: This is the line number 1 和下一行 Written: This is the line number 2

#include <string.h>
#include <stdio.h>
#include <memory.h>
#include <sys/shm.h>
#include <unistd.h>


void main()
{
key_t Clave;
int Id_Memoria;
int *Memoria = NULL;
int i,j;



Clave = ftok ("/bin/ls", 33);
if (Clave == -1)
{
printf("No consigo clave para memoria compartida");
exit(0);
}


Id_Memoria = shmget (Clave, 1024, 0777 | IPC_CREAT);
if (Id_Memoria == -1)
{
printf("No consigo Id para memoria compartida");
exit (0);
}


Memoria = (int *)shmat (Id_Memoria, (char *)0, 0);
if (Memoria == NULL)
{
printf("No consigo memoria compartida");
exit (0);
}



for (j=0; j<100; j++)
{
Memoria[j] = j;
printf( "Written: %d \n" ,Memoria[j]);
}




shmdt ((char *)Memoria);
shmctl (Id_Memoria, IPC_RMID, (struct shmid_ds *)NULL);
}

最佳答案

您需要将字符串逐字符复制到共享内存。指向共享内存中变量的实际指针需要保留在外部,因为共享内存可以位于不同进程中的不同地址。 (您可以使用增量指针,但它们在 C++ 中要容易得多 boost::offset_ptr )

对于操作字符串,string.h 中有字符串实用函数。特别strncpy将字符串移动到不同的内存位置时非常有用。

此外,使用新的 posix 共享内存而不是当前的 sysv 实现也是个好主意。您可以在 shm_overview 中查看有关 posix 共享内存的更多详细信息手册页。当然,如果您有一个仅支持 sysv 接口(interface)的旧操作系统,那么您必须坚持使用旧的 api。

关于c - 将字符串存储在共享内存 C 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40200227/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com