使用C语言编写程序创建两个进程,其中,发送进程过程为: (1)发送进程通过shmget()创建一块共享内存,然后通过shmat()将该共享内存附接到自己的虚拟地址空间中 (2)发送进程通过strcat()追加信息到共享内存中 (3)最后,将共享内存从自己的虚拟地址空间中断开 接收进程: (1)通过shmget()获得对共享内存的权限 (2)通过shmat()将其附接到自己的虚拟地址空间中,同时一次性的输出信息 (3)断开与自己虚拟地址空间的链接,并通过shmctl()撤销共享内存。
时间: 2023-06-13 09:06:43 浏览: 54
以下是使用C语言编写程序创建两个进程的代码:
发送进程:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/shm.h>
#define SHM_SIZE 1024
int main() {
int shmid;
char *shmaddr;
key_t key = ftok(".", 'a'); // 生成key值
// 创建共享内存
if ((shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666)) == -1) {
perror("shmget error");
exit(EXIT_FAILURE);
}
// 将共享内存附接到自己的虚拟地址空间中
if ((shmaddr = shmat(shmid, NULL, 0)) == (void *)-1) {
perror("shmat error");
exit(EXIT_FAILURE);
}
// 追加信息到共享内存中
strcat(shmaddr, "Hello, this is the message from sender process!");
// 断开共享内存连接
if (shmdt(shmaddr) == -1) {
perror("shmdt error");
exit(EXIT_FAILURE);
}
return 0;
}
```
接收进程:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/shm.h>
#define SHM_SIZE 1024
int main() {
int shmid;
char *shmaddr;
key_t key = ftok(".", 'a'); // 生成key值
// 获取共享内存权限
if ((shmid = shmget(key, SHM_SIZE, 0666)) == -1) {
perror("shmget error");
exit(EXIT_FAILURE);
}
// 将共享内存附接到自己的虚拟地址空间中
if ((shmaddr = shmat(shmid, NULL, 0)) == (void *)-1) {
perror("shmat error");
exit(EXIT_FAILURE);
}
// 输出信息
printf("Received message: %s\n", shmaddr);
// 断开共享内存连接
if (shmdt(shmaddr) == -1) {
perror("shmdt error");
exit(EXIT_FAILURE);
}
// 撤销共享内存
if (shmctl(shmid, IPC_RMID, NULL) == -1) {
perror("shmctl error");
exit(EXIT_FAILURE);
}
return 0;
}
```
在执行发送进程后,执行接收进程即可输出信息。注意,需确保发送进程先执行,否则接收进程会无法获取共享内存权限。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)