共享内存例子-线程通信

//主线程往内存中写数据,thread_proc从共享内存中毒数据

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <pthread.h>
#include <error.h>
#include <signal.h>


#define SHM_SIZE (20 * 1024 * 1024) // 20M

static key_t SHM_KEY = 12345;

static int shm_id = -1;
static int running = 1;

void * thread_proc(void *p)
{
 char *buf; 
 int shmid = shmget(SHM_KEY, SHM_SIZE, 0666);
 if (shm_id == -1)
 {
  perror("get share memory");
  return NULL;
 }
 
 buf = (char *)shmat(shmid, NULL, 0);
 
 while(running)
 {
  sleep(1);
  printf("%s/n", buf);
 } 
 return 0;
}

void exit_do()
{
 if (shm_id != -1)
 {
  if (shmctl(shm_id, IPC_RMID, 0) == -1)
  {
   perror("delete share memory");
  }
 }  
}

void sig_do(int sig)
{
 running = 0;
 exit(0);
}

int main()
{
 pthread_t pid;
 char *buf;
 int i = 0;
 
 atexit(exit_do);
 signal(SIGINT, sig_do);
  
 shm_id = shmget(SHM_KEY, SHM_SIZE, IPC_CREAT|0666);
 if (shm_id == -1)
 {
  perror("create share memory");
  return -1;
 }
 
 buf = shmat(shm_id, NULL, 0);
 
 pthread_create(&pid, NULL, thread_proc, NULL);
 while(1)
 {
  sprintf(buf, "This is a test! times: %d", i++);
  sleep(1);
 }
 return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值