Linuxc之共享内存

1.创建共享内存,写进程每隔2秒向内存写入一次“hello world”;
 如果结束写操作,则写进程写入“end”;
 
2.读进程从共享内存读取数据,并打印。直到读到“end”为止。


源代码:
write.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
char* make_shmid()
{
 int  shmid;
 char *p = NULL;
 shmid=shmget(4321,4096,IPC_CREAT);
 p = shmat(shmid,NULL,0);
 return p;
}
void make_write(char *a)
{
 char w_buff[15] = "Hello world";
  sleep(2);
  strcpy(a,w_buff);
}
void tt(int sig)
{
 char *a;
 a=make_shmid();
 char end_buf[5] = "end";
 strcpy(a,end_buf);
 exit(0);
}
int main()
{
 char *a;
 a=make_shmid();
 while(1)
 {
  make_write(a);
  signal(SIGINT,tt);
 }
 shmdt(a);
 return 0;
}

read.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
int main(void)
{
 int shm_id;
 shm_id = shmget(4321,4096,IPC_CREAT);
 if(shm_id == -1)
 {
  perror("shmget error");
  exit(1);
 }
 char *r_buff;
 while(1){
  r_buff = shmat(shm_id,NULL,0);
  if((strcmp(r_buff,"end")) != 0){
  printf("%s\n",r_buff);
  memset(r_buff,'\0',strlen(r_buff));
  sleep(2);
  }
  else{
   printf("%s\n",r_buff);
   break;
  }

 }
 shmdt(r_buff);
 shmctl(shm_id,IPC_RMID,NULL);
 return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37192076/article/details/80777864