编写c程序实现共享内存操作 程序1向共享内存写入键盘输入的数据; 程序2从共享内存读取程序1的数据并打印; 两个程序都使用while(1)循环执行,直到强制退出。
时间: 2024-05-05 07:22:08 浏览: 13
下面是编写的C程序实现共享内存操作:
程序1:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/shm.h>
#define SHM_KEY 0x1234
#define BUF_SIZE 1024
int main()
{
int shmid;
char *shmaddr;
char input[BUF_SIZE];
// 创建共享内存
shmid = shmget(SHM_KEY, BUF_SIZE, IPC_CREAT | 0666);
if (shmid == -1) {
perror("shmget");
exit(EXIT_FAILURE);
}
// 将共享内存连接到当前进程的地址空间
shmaddr = shmat(shmid, NULL, 0);
if (shmaddr == (void *) -1) {
perror("shmat");
exit(EXIT_FAILURE);
}
while (1) {
printf("Enter some text: ");
fgets(input, BUF_SIZE, stdin);
// 将输入的数据写入共享内存
strncpy(shmaddr, input, BUF_SIZE);
if (strcmp(input, "quit\n") == 0)
break;
}
// 分离共享内存
if (shmdt(shmaddr) == -1) {
perror("shmdt");
exit(EXIT_FAILURE);
}
return 0;
}
```
程序2:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/shm.h>
#define SHM_KEY 0x1234
#define BUF_SIZE 1024
int main()
{
int shmid;
char *shmaddr;
char output[BUF_SIZE];
// 获取共享内存
shmid = shmget(SHM_KEY, BUF_SIZE, 0666);
if (shmid == -1) {
perror("shmget");
exit(EXIT_FAILURE);
}
// 将共享内存连接到当前进程的地址空间
shmaddr = shmat(shmid, NULL, 0);
if (shmaddr == (void *) -1) {
perror("shmat");
exit(EXIT_FAILURE);
}
while (1) {
// 从共享内存读取数据
strncpy(output, shmaddr, BUF_SIZE);
printf("Received: %s", output);
if (strcmp(output, "quit\n") == 0)
break;
}
// 分离共享内存
if (shmdt(shmaddr) == -1) {
perror("shmdt");
exit(EXIT_FAILURE);
}
// 删除共享内存
if (shmctl(shmid, IPC_RMID, 0) == -1) {
perror("shmctl");
exit(EXIT_FAILURE);
}
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)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)