今天学习了linux下进程通信方式的内存共享,主要的函数int shmget(key_t key,int size,int flags);char *shmat(int shmid,char *shmaddr,int flags);int shmdt(char *shmaddr);int shmctl(int shmid,int cmd,shmid_ds *buf);明白了怎样实现进程之间内存共享,这只是实现了功能,但没有应用。
void server(void)
{
int shmid;
void *shmdata;
char *buffer;
shmid=shmget(IPC_PRIVATE,SHMDATASIZE,IPC_CREAT|SHM_R|SHM_W);
shmdata=shmat(shmid,0,0);
shmctl(shmid,IPC_RMID,NULL);
*(int*)shmdata=semid;
printf("%d",semid);
buffer=shmdata+sizeof(int);
printf("server is running with id %d/n",shmid);
fflush(stdout);
printf("enter message:");
fgets(buffer,BUFFERSIZE,stdin);
sleep(10);
}
int client(int argc,char **argv)
{
int semid;
char *buffer;
void *shmdata;
int shmid=atoi(argv[1]);
shmdata=shmat(shmid,0,0);
semid=*(int *)shmdata;
buffer=shmdata+sizeof(int);
printf("client operational:shm id is %d/n",shmid);
printf("%s",buffer);
return 0;
}
内存的共享配合信号量的使用,将可以让内存不出现错误共享