linux 练习四 共享内存练习

题目:编写两个进程,a和b,利用共享内存技术,a向共享内存写字符串,b从共享内存把字符串读出来,并显示在屏幕上


/* 目标 编写两个进程a和b,利用共享内存技术,
 * a向共享内存写字符串,b从共享内存中读取
 * 字符串并显示在屏幕上 */

shmwrite.c

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

int main(int argc, char * argv[])
{
    int fd;
    char buf[20];
    char *shmaddr = NULL;
    char* tempstr = "write some data to share aread";
    int shmd = shmget(IPC_PRIVATE,1000,O_RDWR|O_CREAT|0666);
    if(shmd < 0)
    {
        perror("shmget");
        exit(1);
    }
    fd = open("shmaddr",O_WRONLY | O_CREAT | O_TRUNC,666);
    if(fd < 0)
    {
        perror("open");
        exit(1);
    }
    sprintf(buf,"shmfd=%d\n",shmd);
    if( write(fd,buf,strlen(buf)) < 0)
    {
        perror("write");
        exit(1);
    }

    shmaddr = shmat(shmd,NULL,0);

    printf("shmaddr =%p,shmd=%d\n",shmaddr,shmd);
    if(((long int)shmaddr) < 0)
    {
        shmctl(shmd,IPC_RMID,0);
        perror("shmat");
        exit(1);
    }
    sprintf(buf,"i'm a process\n");
    memcpy(shmaddr, tempstr,strlen(tempstr));
   printf("%s\n",shmaddr);
    sleep(5);
    if(shmaddr[0] == 2)
    {
        printf("b process set 2\n");
    }
    printf("wait 5s time over\n");
    if(((int)(shmdt(shmaddr))) < 0)
    {
        printf("shmaddr =%p\n",shmaddr);
        perror("shmdt");
  
    }
    if( shmctl(shmd,IPC_RMID,0) < 0)
    {
        perror("shmctl");
    }
}

//shmread.c
#include <stdlib.h>
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
int main(int argc,char * argv[])
{
    int fd;
    char buf[30];
    char *shmidprt;
    int shmid;
    char * shmaddr;
    if(argc < 2)
    {
        printf("please input file name\n");
        exit(1);
    }

    fd = open(argv[1],O_RDONLY);
    if(fd < 3)
    {
        perror("open");
        exit(1);
    }
    
    if((read(fd,buf,sizeof(buf)) < 0))
    {
        perror("read");
        exit(1);
    }
    if( close(fd) < 0)
    {
        perror("close");
    }
    shmidprt = strchr(buf,'=');
    shmid = atoi(shmidprt+1);
    printf("shmid = %d\n",shmid);
    shmaddr = shmat(shmid,NULL,0);
    if((long int)(shmaddr) < 0)
    {
        perror("shmat");
        exit(1);
    }

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

    *shmaddr = 2;

    if(shmdt(shmaddr) < 0)
    {
        perror("shmdt");
        exit(1);
    }

}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值