将字符串存储在共享内存 C

Store an string on a Shared Memory C

您好,这段代码在共享内存整数上存储时工作正常,但我想存储字符串,我该如何修改它才能做到这一点?
例如,输出将是 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);
}

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

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

此外,最好使用新的 posix 共享内存而不是当前的 sysv 实现。您可以在 shm_overview 手册页中查看有关 posix 共享内存的更多详细信息。当然,如果你有一个旧的 OS 只支持 sysv 接口,那么你必须坚持使用旧的 api.