test7_3a.c:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include<errno.h>
#include<string.h>
#define BUF_SIZE 1024
int main(void)
{
int shmid;
char *shmptr;
char *B = "exit";
key_t key;
if((key = ftok("/dev/null", 1)) < 0)
{
printf("ftok error:%s/n", strerror(errno));
return -1;
}
if((shmid = shmget(key, BUF_SIZE, IPC_CREAT|0666)) == -1)// create share mem
{
printf("shmget error!/n");
exit(1);
}
if((shmptr = shmat(shmid, NULL, 0)) == (void *)-1)//attch share mem
{
fprintf(stderr, "shmat error!/n");
exit(1);
}
while(1)
{
printf("string:%s/n", shmptr);
sleep(5);
if(strcmp(shmptr, "exit") == 0)
exit(0);
}
exit(0);
}
--------------------------------------------------------
test7_3b.c:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include<errno.h>
#include<string.h>
#define BUF_SIZE 1024
int main(void)
{
int shmid;
char *shmptr;
key_t key;
if((key = ftok("/dev/null", 1)) < 0)
{
printf("ftok error:%s/n", strerror(errno));
return -1;
}
if((shmid=shmget(key, BUF_SIZE, IPC_CREAT|0666))==-1)
{
printf("shmget error!/n");
printf("Faile reason:%s./n",sys_errlist[errno]);
exit(1);
}
if((shmptr=shmat(shmid,NULL,0))==(void*)-1)
{
fprintf(stderr,"shmat error!/n");
printf("Faile reason:%s./n",sys_errlist[errno]);
exit(1);
}
while(1)
{
printf("input a string:");
scanf("%s",shmptr);
if(strcmp(shmptr, "exit") == 0)
exit(0);
}
exit(0);
}
在两个终端分别运行。