共享内存的读写

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define BUFFER_SIZE 2048

int main()
{
    pid_t pid;
    int shmid;
    char *shm_addr;
    char flag[]="parent";
    char buff[BUFFER_SIZE];

    if((shmid = shmget(IPC_PRIVATE,BUFFER_SIZE,0666)) < 0)
    {
       perror("shmget");
       exit(1);
    }
    else
        printf("create share memory!\n");

    if((pid = fork()) < 0 )
    {
        perror("fork");
        exit(1);
    }
    else if(pid == 0)
    {
        if((shm_addr = shmat(shmid,0,0)) == (void *)-1)
        {
            perror("child:shmat\n");
            exit(1);
        }
        else 
            printf("child:Attach shared memory:%p\n",shm_addr);

        while(strncmp(shm_addr,flag,strlen(flag)))
        {
            printf("child: waiting for data...\n");
            sleep(3);
        }

        strcpy(buff,shm_addr + strlen(flag));
        printf("child:shared memory:%s\n",buff);

        if(shmdt(shm_addr) < 0)
        {
            perror("child:shmdt");
            exit(1);
        }
        else
            printf("child:detached shared memory\n");
    }
    else
    {
        sleep(1);
        if((shm_addr = shmat(shmid,(void *)0,0)) == (void *)-1)
        {
            perror("parent:shmat\n");
            exit(1);
        }
        else
        {
            printf("parent attach share memory:%p\n",shm_addr);
        }

        sleep(1);
        printf("input string:\n");

        fgets(buff,BUFFER_SIZE-strlen(flag),stdin);

        strncpy(shm_addr+strlen(flag),buff,strlen(buff));
        strncpy(shm_addr,flag,strlen(flag));

        if(shmdt(shm_addr) < 0)
        {
             perror("parent:shmdt");
             exit(1);
        }
        else
            printf("parent: deattach shared memory\n");

        waitpid(pid,NULL,0);

        if(shmctl(shmid,IPC_RMID,NULL) == -1)
        {
            perror("shmctl:IPC_RMID");
            exit(1);
        }
        else
            printf("delete shared memory\n");

        printf("finished!\n");
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值