Linux下共享内存及线程的创建
2017-03-16 15:32
309 查看
共享内存的创建
接口的.h文件
.c文件
测试用例
server.c文件
client.c
线程的创建
.c文件
Makefile文件
结果截图
接口的.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
结果截图
相关文章推荐
- Linux 共享内存的创建,控制,脱离和删除
- Linux下创建共享内存和测试
- 将 Win32 C/C++ 应用程序迁移到 POWER 上的 Linux,第 1 部分: 进程、线程和共享内存服务 (转载)
- 将 Win32 C/C++ 应用程序迁移到 POWER 上的 Linux,第 1 部分: 进程、线程和共享内存服务
- linux创建线程时,需注意线程内存回收问题!
- 最简单的linux线程创建、共享变量
- Linux下的共享内存(02)---创建共享内存
- 将Win32 C/C++应用程序迁移到Linux-进程、线程和共享内存
- 将 Win32 C/C++ 应用程序迁移到 POWER 上的 Linux,第 1 部分: 进程、线程和共享内存服务
- 将 Win32 C/C++ 应用程序迁移到 POWER 上的 Linux,第 1 部分: 进程、线程和共享内存服务 (转)
- Linux下线程的创建
- linux 共享内存映射原理1 vmalloc kmalloc getfreepage
- Linux环境进程间通信(五): 共享内存(下)
- Linux环境进程间通信(五): 共享内存(上)
- Linux中共享内存及内存映射技术研究
- Linux环境进程间通信(五): 共享内存(下)
- linux 文件操作函数 通过例子来解释 父子间文件描述符共享 内存映像图
- Linux环境进程间通信: 共享内存
- Linux环境进程间通信(五): 共享内存(上)
- linux下的简单共享内存map实现