linux共享内存
2015-11-01 00:00
423 查看
#include <stdio.h> #include <string.h> #include <semaphore.h> #include <sys/shm.h> #include <unistd.h> #include <fcntl.h> #define BUFFER_SIZE 4 int main() { int shmid = shmget((key_t)1234, sizeof(int) * BUFFER_SIZE, 0644 | IPC_CREAT); if ( -1 == shmid ) { printf("shmget failed!\n"); return 0; } void *shm = shmat(shmid, NULL, 0); if ((void *)-1 == shm) { printf("shmat failed!\n"); return 0; } int *sharedbuffer = (int *)shm; memset(sharedbuffer, -1, sizeof(int) * BUFFER_SIZE); int index = 0; while (index <= 20) { for (int i = 0; i < 4; i++) { if (-1 == sharedbuffer[i]) { sharedbuffer[i] = ++index; printf("product: %d\n", sharedbuffer[i]); break; } } } if (-1 == shmdt((void *)sharedbuffer)) { printf("shmdt failed!\n"); } }
#include <stdio.h> #include <string.h> #include <semaphore.h> #include <sys/shm.h> #include <unistd.h> #include <fcntl.h> #define BUFFER_SIZE 4 int main() { int shmid = shmget((key_t)1234, sizeof(int) * BUFFER_SIZE, 0644 | IPC_CREAT); if ( -1 == shmid ) { printf("shmget failed!\n"); return 0; } void *shm = shmat(shmid, NULL, 0); if ((void *)-1 == shm) { printf("shmat failed!\n"); return 0; } int *sharedbuffer = (int *)shm; int run = 1; while (run) { for (int i = 0; i < 4; i++) { if (-1 != sharedbuffer[i]) { printf("consumer: %d\n", sharedbuffer[i] ); if ( 20 == sharedbuffer[i] ) { run = 0; } sharedbuffer[i] = -1; break; } } } if (-1 == shmdt((void *)sharedbuffer)) { printf("shmdt failed!\n"); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
相关文章推荐
- CentOS 7安裝视频解码器
- centos安装ssh免密码登录
- CentOS设置打开终端快捷键
- CentOS 搭建hadhoop单机模式
- CentOS删除多余的启动项
- 修改SecureCRT终端的Home和End功能键
- 刚装完CentOS后连不上网
- CentOS安装mysql并授权远程登录
- CentOS 将网卡设置成eth0
- install google-chrome on CentOS 7
- centos 下 g++ 安装
- linux下的mv命令与系统rename关系
- 修复MBR的工具MBRFix下载
- "Couldn't resolve host 'mirrorlist.centos.org'"
- ubuntu解决arm-linux-gcc no such file的问题
- ubuntu14.0安装arm-linux-gcc交叉编译环境
- 鸟哥的linux私房菜(RIDA摘录)
- linux 多线程
- Linux Top 命令
- centos 安装KVM及使用