linux 进程通信之共享内存

 
 

一,创建共享内存

void *shmat(int shmid, void *shmaddr, int shmflg);该系统调用将shmid 对应的共享内存区映射到进程的虚拟地址空间中,shmaddr 为指定的映射起始地址,其值为NULL 时,映射空间由系统确定;shmflg 为标志字,其值一般指定为0。

/*
 * mkshm.c - Create and initialize shared memory segment
 */
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>

#define BUFSZ 4096 /* Size of the segment */
int main(void)
{
   int shmid;  

    if((shmid = shmget(IPC_PRIVATE, BUFSZ, IPC_CREAT | 0666)) < 0) {
     perror("shmget");
   exit(EXIT_FAILURE);
    }

    printf("segment created: %d\n", shmid);
    system("ipcs -m");
    exit(EXIT_SUCCESS);
}


查看目前已有的共享内存命令:ipcs -m

 二,向共享内存中写入数据

/*
 * wrshm.c - Write data to a shared memory segment
 */
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <ctype.h>
#include <unistd.h>

#define BUFSZ 4096

int main(int argc, char *argv[])
{
    int shmid;			/* Segment ID */
    char *shmbuf;		/* Address in process */
    key_t key;
    char *msg;
    int len;
        
    key = ftok("/tmp", 0); 

    if((shmid = shmget(key, BUFSZ, IPC_CREAT|0666)) < 0) {
        perror("shmget");
        exit(EXIT_FAILURE);
    }

    printf("segment created: %d\n", shmid);
    system("ipcs -m");
    
    /* Attach the segment */
    if((shmbuf = (char *)shmat(shmid, 0, 0)) < 0) {
	    perror("shmat");
	    exit(EXIT_FAILURE);
    }
    
    /* Write message to the segment */
    msg = "this is the message written by wrshm program.";
    len = strlen(msg);
    strcpy(shmbuf, msg);
	
    printf("%s\nTotal %d characters written to shared memory.\n", msg, len);
    
    /* De-attach the segment */
    if(shmdt(shmbuf) < 0) {
	    perror("shmdt");
	    exit(EXIT_FAILURE);
    }
    
    exit(EXIT_SUCCESS);
}


三,从共享内存中读入数据

/*
 * wrshm.c - Write data to a shared memory segment
 */
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <ctype.h>
#include <unistd.h>

#define BUFSZ 4096

int main(int argc, char *argv[])
{
    int shmid;			/* Segment ID */
    char *shmbuf;		/* Address in process */
    key_t key;
    int len;
            
    key = ftok("/tmp", 0);
    /* get the same share memory block */ 
    if((shmid = shmget(key, 0, 0)) < 0) {
        perror("shmget");
        exit(EXIT_FAILURE);
    }        
    
    /* Attach the segment */
    if((shmbuf = (char *)shmat(shmid, 0, 0)) < 0) {
	    perror("shmat");
	    exit(EXIT_FAILURE);
    }
    
    /* read from share memory */
    printf("Info read form shared memory is:\n%s\n", shmbuf);
    
    /* De-attach the segment */
    if(shmdt(shmbuf) < 0) {
	    perror("shmdt");
	    exit(EXIT_FAILURE);
    }
    
    exit(EXIT_SUCCESS);
}


 

你可能感兴趣的:(linux,linux,linux,进程通信,共享内存)