Linux 进程间通信之共享内存实例

共享内存是不同进程间通过访问同一段逻辑内存,实现数据共享,非常方便。下面是一个简单实例

在share_write.c中

#include 
#include 
#include 
#include 
#include 

int main(int argc, char *argv[])
{
    int shmid = 0;
    int share_len = 64;
    void *shm = NULL;
    
    shmid = shmget((key_t)1000, share_len, 0666 | IPC_CREAT);
    if (shmid == -1)
    {
        printf("shmget fail\n");
    }

    shm = shmat(shmid, 0, 0);
    if (shm == (void *) - 1)
    {
        printf("shmat fail\n");
    }

    strcpy(shm, "TEST");
    printf("Contents of share memory: %s\n", shm);

    if (shmdt(shm) == -1)
   {
        printf("shmdt fail\n");
    }

    return 0;
}

在share_read.c中

#include 
#include 
#include 
#include 
#include 

int main(int argc, char *argv[])
{
    int shmid = 0;
    int share_len = 64;
    void *shm = NULL;

    shmid = shmget((key_t)1000, share_len, 0666 | IPC_CREAT);
    if (shmid == -1)
    {
        printf("shmget fail\n");
    }

    shm = shmat(shmid, 0, 0);
    if (shm == (void *) - 1)
    {
        printf("shmat fail\n");
    }

    printf("Contents of share memory: %s\n", shm);


    if (shmdt(shm) == -1)

   {
        printf("shmdt fail\n");
 
   }

    if (shmctl(shmid, IPC_RMID, 0) == -1)

   {
        printf("shmctl fail\n");

   }

    return 0;
}

示例说明share_write向共享内存段写入数据,share_read读出共享内存段数据,运行结果如下

Linux 进程间通信之共享内存实例_第1张图片

 

示例中涉及的几个函数

int shmget(key_t key, size_t size, int shmflg);  // 分配共享内存段

void *shmat(int shmid, const void *shmaddr, int shmflg); //连接共享内存到当前进程地址空间

int shmdt(const void *shmaddr); //删除连接

int shmctl(int shmid, int cmd, struct shmid_ds *buf); //根据标识符shmid执行cmd控制操作,如销毁分配的共享内存段

你可能感兴趣的:(linux,c语言,多进程)