linux进程通信-共享内存

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

int main()
{
    key_t key;        // 用于打开指定的共享内存
    int shm_id;        // 共享内存id
    char *p;        // 用于映射共享内存到进程空间

    key = ftok("/dev/null", 0);

    shm_id = shmget(key, 7, IPC_CREAT|0666);

    p = (char *)shmat(shm_id, NULL, 0);

    // memset(p, 'A', 6);
    strcpy(p, "hello");

    shmdt(p);

    return 0;
}
#include <stdio.h>
#include <sys/shm.h>
#include <unistd.h>
#include <string.h>

int main()
{
    key_t key;        // 用于打开指定的共享内存
    int shm_id;        // 共享内存id
    char *p;        // 用于映射共享内存到进程空间

    key = ftok("/dev/null", 0);

    shm_id = shmget(key, 6, 0666);

    struct shmid_ds shm_buf;

    shmctl(shm_id, IPC_STAT, &shm_buf);
    
    printf("len :%d\n", shm_buf.shm_segsz);

    p = (char *)shmat(shm_id, NULL, 0);

    printf("%s\n",p);

    shmdt(p);

    shmctl(shm_id, IPC_RMID, 0);
    return 0;
}

 

posted @ 2021-12-28 09:05  roverqqq  阅读(42)  评论(0)    收藏  举报