用c语言编写一段程序,使其用共享存储区来实现两个进程之间的进程通信。进程A创建一个长度为 512字节的共享内存,并显示写入该共享内存的数据;进程B将共享内存附加到自己的地址空间,并向共享内存中写入数据。
时间: 2024-02-01 09:13:15 浏览: 29
以下是一个简单的使用共享内存进行进程间通信的示例程序,使用了 POSIX 标准库。
进程A的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#define SHM_SIZE 512
int main()
{
int shm_fd;
char *shm_ptr;
const char *message = "Hello, Process B!";
// 创建共享内存
shm_fd = shm_open("/my_shm", O_CREAT | O_RDWR, 0666);
if (shm_fd == -1) {
perror("shm_open failed");
exit(1);
}
// 调整共享内存大小
if (ftruncate(shm_fd, SHM_SIZE) == -1) {
perror("ftruncate failed");
exit(1);
}
// 映射共享内存到进程地址空间
shm_ptr = mmap(NULL, SHM_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
if (shm_ptr == MAP_FAILED) {
perror("mmap failed");
exit(1);
}
// 写入数据到共享内存
strncpy(shm_ptr, message, strlen(message));
printf("Process A wrote message: %s\n", message);
// 解除映射并关闭共享内存
if (munmap(shm_ptr, SHM_SIZE) == -1) {
perror("munmap failed");
exit(1);
}
if (close(shm_fd) == -1) {
perror("close failed");
exit(1);
}
return 0;
}
```
进程B的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#define SHM_SIZE 512
int main()
{
int shm_fd;
char *shm_ptr;
// 打开共享内存
shm_fd = shm_open("/my_shm", O_RDWR, 0666);
if (shm_fd == -1) {
perror("shm_open failed");
exit(1);
}
// 映射共享内存到进程地址空间
shm_ptr = mmap(NULL, SHM_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
if (shm_ptr == MAP_FAILED) {
perror("mmap failed");
exit(1);
}
// 从共享内存读取数据
printf("Process B read message: %s\n", shm_ptr);
// 写入数据到共享内存
const char *message = "Hello, Process A!";
strncpy(shm_ptr, message, strlen(message));
// 解除映射并关闭共享内存
if (munmap(shm_ptr, SHM_SIZE) == -1) {
perror("munmap failed");
exit(1);
}
if (close(shm_fd) == -1) {
perror("close failed");
exit(1);
}
return 0;
}
```
这两个进程使用共享内存进行通信,进程A创建了一个长度为 512 字节的共享内存,并向其中写入了一条消息,进程B将共享内存映射到自己的地址空间,并从中读取数据后向其中写入了另一条消息。
注意,在实际使用中需要进行错误处理,特别是在多个进程共享同一个共享内存时需要进行同步和互斥操作,以免出现数据竞争和意外情况。