共享内存的创建
接口的.h文件
#ifndef _COMM_H
#define _COMM_H
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<unistd.h>
#define PATHNAME "."
#define PROJ_ID 06666
static int Comm(int size,int flag);
int Creat(int size);//创建
int Get();//获取
int Destory(int shimd);//销毁
char* Shmat(int shmid);//共享内存的挂接
int Shmdt(const char* addr);//删除链接
#endif
.c文件
#include"comm.h"
static int Comm(int size,int flag)
{
key_t key = ftok(PATHNAME,PROJ_ID);
int shmid = shmget(key,size,flag);
if(shmid < 0 )
{
perror("shmget");
return -1;
}
return shmid;
}
int Creat(int size)//创建
{
return Comm(size,IPC_CREAT|IPC_EXCL|0x666);
}
int Get()//获取
{
return Comm(0,IPC_EXCL);
}
int Destory(int shmid)//销毁
{
if(shmctl(shmid,IPC_RMID,NULL)<0)
{
perror("shmctl");
return -1;
}
return 0;
}
char* Shmat(int shmid)//共享内存的挂接
{
char* ret = shmat(shmid,NULL,0);
if(ret == (char*)-1)
{
perror("shmat");
return NULL;
}
return ret;
}
int Shmdt(const char* addr)
{
if(shmdt(addr) < 0)
{
perror("shmdt");
return -1;
}
return 0;
}
测试用例
server.c文件
#include"comm.h"
int main()
{
int shimd = Creat(4096);
char* buf = Shmat(shimd);
int i = 0;
while(i < 4096)
{
buf[i] = 'a' + i%26;
buf[i+1] = '\0';
i++;
sleep(2);
}
Destory(shimd);
return 0;
}
client.c
#include"comm.h"
int main()
{
int shmid = Get();
char* buf = Shmat(shmid);
int i = 0;
while(i < 4096)
{
printf("%s\n",buf);
i++;
sleep(2);
}
return 0;
}
线程的创建
.c文件
#include<stdio.h>
#include<pthread.h>
#include<sys/types.h>
#include<unistd.h>
void thread()
{
while(1)
{
printf("new thread tid = %lu pid = %d\n",pthread_self(),getpid());
sleep(1);
}
}
int main()
{
pthread_t id;
int ret = pthread_create(&id,NULL,(void*)thread,NULL);
if(ret != 0)
{
printf("Creat error!\n");
return -1;
}
while(1)
{
printf("man thread tid = %lu pid = %d\n",pthread_self(),getpid());
sleep(1);
}
return 0;
}
Makefile文件
mypthread:mypthread.c
gcc -o $@ $^ -lpthread
.PHONY:clean
clean:
rm -f mypthrea
结果截图