(2)编写c程序实现共享内存操作 程序1向共享内存写入键盘输入的数据; 程序2从共享内存读取程序1的数据并打印; 两个程序都使用while(1)循环执行,直到强制退出。
时间: 2024-05-04 12:20:46 浏览: 16
程序1:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_SIZE 1024
int main() {
key_t key = ftok(".", 's');
if (key == -1) {
perror("ftok error");
exit(1);
}
int shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666);
if (shmid == -1) {
perror("shmget error");
exit(1);
}
char *shmaddr = (char *) shmat(shmid, NULL, 0);
if (shmaddr == (char *) -1) {
perror("shmat error");
exit(1);
}
while (1) {
printf("Enter message: ");
fgets(shmaddr, SHM_SIZE, stdin);
printf("Message written to shared memory: %s", shmaddr);
sleep(1);
}
if (shmdt(shmaddr) == -1) {
perror("shmdt error");
exit(1);
}
if (shmctl(shmid, IPC_RMID, NULL) == -1) {
perror("shmctl error");
exit(1);
}
return 0;
}
```
程序2:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_SIZE 1024
int main() {
key_t key = ftok(".", 's');
if (key == -1) {
perror("ftok error");
exit(1);
}
int shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666);
if (shmid == -1) {
perror("shmget error");
exit(1);
}
char *shmaddr = (char *) shmat(shmid, NULL, 0);
if (shmaddr == (char *) -1) {
perror("shmat error");
exit(1);
}
while (1) {
printf("Message read from shared memory: %s", shmaddr);
sleep(1);
}
if (shmdt(shmaddr) == -1) {
perror("shmdt error");
exit(1);
}
return 0;
}
```
说明:
这两个程序都使用了 `ftok()` 函数生成共享内存的 key 值,然后调用 `shmget()` 函数创建共享内存。程序1通过调用 `shmat()` 函数将共享内存映射到进程的地址空间中,并通过 `fgets()` 函数从键盘读取输入,并将输入写入共享内存中。程序2也通过 `shmat()` 函数将共享内存映射到进程的地址空间中,并通过 `printf()` 函数从共享内存中读取数据并打印。这两个程序都使用了无限循环 `while (1)`,直到被强制退出。程序退出时,需要调用 `shmdt()` 函数将共享内存从进程的地址空间中分离,并调用 `shmctl()` 函数删除共享内存。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)