//主线程往内存中写数据,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;
}