编写一段C语言程序使其完成:两段程序 test1和test2通过一个共享内存进行通信,其中test1 向共享内存中写数据,test2从共享内存中读出数据或信息并将数据或信息送入标准输出上。
时间: 2024-05-11 10:16:12 浏览: 25
下面是代码实现:
test1.c:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/shm.h>
#define SHM_SIZE 1024
int main(void) {
int shmid;
char *shmaddr;
char *msg = "Hello, test2!";
// 创建共享内存
shmid = shmget(IPC_PRIVATE, SHM_SIZE, IPC_CREAT|0666);
if (shmid < 0) {
perror("error: shmget()");
exit(EXIT_FAILURE);
}
// 映射共享内存
shmaddr = (char *)shmat(shmid, NULL, 0);
if (shmaddr == (char *)(-1)) {
perror("error: shmat()");
exit(EXIT_FAILURE);
}
// 向共享内存写入数据
snprintf(shmaddr, SHM_SIZE, "%s", msg);
// 打印写入的数据
printf("test1: write message to share memory: '%s'\n", msg);
// 分离共享内存
if (shmdt(shmaddr) < 0) {
perror("error: shmdt()");
exit(EXIT_FAILURE);
}
return 0;
}
```
test2.c:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/shm.h>
#define SHM_SIZE 1024
int main(void) {
int shmid;
char *shmaddr;
// 获取共享内存
shmid = shmget(IPC_PRIVATE, SHM_SIZE, IPC_CREAT|0666);
if (shmid < 0) {
perror("error: shmget()");
exit(EXIT_FAILURE);
}
// 映射共享内存
shmaddr = (char *)shmat(shmid, NULL, 0);
if (shmaddr == (char *)(-1)) {
perror("error: shmat()");
exit(EXIT_FAILURE);
}
// 从共享内存读取数据
printf("test2: read message from share memory: '%s'\n", shmaddr);
// 分离共享内存
if (shmdt(shmaddr) < 0) {
perror("error: shmdt()");
exit(EXIT_FAILURE);
}
return 0;
}
```
编译链接:
```bash
$ gcc -o test1 test1.c
$ gcc -o test2 test2.c
```
运行:
```bash
$ ./test1 & ./test2
test1: write message to share memory: 'Hello, test2!'
test2: read message from share memory: 'Hello, test2!'
```
相关推荐
![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)
![](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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)