编写c程序实现共享内存操作 程序1向共享内存写入键盘输入的数据; 程序2从共享内存读取程序1的数据并打印; 两个程序都使用while(1)循环执行,直到强制退出。
时间: 2024-04-30 08:18:30 浏览: 14
以下是一个基本的实现共享内存操作的C程序:
程序1:写入数据到共享内存
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_SIZE 1024 // 共享内存大小
int main() {
key_t key = ftok(".", 'a'); // 获取共享内存的键值
int shmid = shmget(key, SHM_SIZE, IPC_CREAT|0666); // 创建共享内存
if (shmid == -1) {
perror("shmget");
exit(1);
}
char *shmaddr = (char*)shmat(shmid, NULL, 0); // 获取共享内存的地址
if (shmaddr == (void*)-1) {
perror("shmat");
exit(1);
}
while (1) {
printf("请输入要写入共享内存的数据:");
fgets(shmaddr, SHM_SIZE, stdin); // 从键盘读取数据到共享内存
if (strncmp(shmaddr, "quit", 4) == 0) { // 如果输入“quit”,退出循环
break;
}
}
shmdt(shmaddr); // 解除共享内存的连接
shmctl(shmid, IPC_RMID, NULL); // 删除共享内存
return 0;
}
```
程序2:从共享内存读取数据并打印
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_SIZE 1024 // 共享内存大小
int main() {
key_t key = ftok(".", 'a'); // 获取共享内存的键值
int shmid = shmget(key, SHM_SIZE, IPC_CREAT|0666); // 创建或获取共享内存
if (shmid == -1) {
perror("shmget");
exit(1);
}
char *shmaddr = (char*)shmat(shmid, NULL, 0); // 获取共享内存的地址
if (shmaddr == (void*)-1) {
perror("shmat");
exit(1);
}
while (1) {
printf("读取到的数据:%s", shmaddr); // 从共享内存中读取数据并打印
if (strncmp(shmaddr, "quit", 4) == 0) { // 如果读取到“quit”,退出循环
break;
}
sleep(1);
}
shmdt(shmaddr); // 解除共享内存的连接
return 0;
}
```
注意:以上代码只是一个简单的实现,可能会存在一些问题,如死锁和数据同步等问题,实际使用中需要更完善的处理。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)