请在Linux利用c语言写程序,使用共享内存在进程A和进程B之间发送数据,进程A向进程B发送hello,进程B收到进程A的数据hello后发送world给进程A...
时间: 2024-02-09 11:13:11 浏览: 30
好的,这是一个典型的共享内存通信的例子。下面是示例代码:
进程A:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/shm.h>
#define SHM_KEY 0x1234
typedef struct {
char buf[1024];
int len;
} shm_data_t;
int main() {
int shmid;
shm_data_t *shm_data;
shmid = shmget(SHM_KEY, sizeof(shm_data_t), IPC_CREAT|0666);
if (shmid == -1) {
perror("shmget failed");
exit(1);
}
shm_data = (shm_data_t*)shmat(shmid, NULL, 0);
if (shm_data == (shm_data_t*)-1) {
perror("shmat failed");
exit(1);
}
strcpy(shm_data->buf, "hello");
shm_data->len = strlen(shm_data->buf);
while (1) {
if (strncmp(shm_data->buf, "world", 5) == 0) {
break;
}
}
shmdt(shm_data);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
```
进程B:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/shm.h>
#define SHM_KEY 0x1234
typedef struct {
char buf[1024];
int len;
} shm_data_t;
int main() {
int shmid;
shm_data_t *shm_data;
shmid = shmget(SHM_KEY, sizeof(shm_data_t), IPC_CREAT|0666);
if (shmid == -1) {
perror("shmget failed");
exit(1);
}
shm_data = (shm_data_t*)shmat(shmid, NULL, 0);
if (shm_data == (shm_data_t*)-1) {
perror("shmat failed");
exit(1);
}
while (strncmp(shm_data->buf, "hello", 5) != 0) {
// 等待进程A写入共享内存
}
printf("Received data: %s\n", shm_data->buf);
strcpy(shm_data->buf, "world");
shm_data->len = strlen(shm_data->buf);
shmdt(shm_data);
return 0;
}
```
在这个例子中,进程A创建了一个共享内存区域,并向其中写入了一段数据"hello",然后等待进程B向共享内存中写入数据"world"。进程B也连接到了同一个共享内存区域,并等待进程A向共享内存中写入数据"hello",然后读取共享内存中的数据,并向其中写入数据"world"。最后,进程A检测到共享内存中已经写入了数据"world",退出程序。
相关推荐
![](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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)