linux 练习四 共享内存练习

来源:互联网 发布:深圳毕业生入户 知乎 编辑:程序博客网 时间:2024/05/21 10:35

题目:编写两个进程,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);    }}