1、有P1,P2,P3三个进程,P1和P2负责从键盘接收字符串,均发送给P3,P3接收到字符串,根据发送方分别显示”P3 received *** from P1(或P2)" ;用c语言在一个程序中共享存储实现。
时间: 2024-04-30 18:21:35 浏览: 121
以下是使用共享内存实现的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_KEY 1234
#define BUFFER_SIZE 1024
int main() {
int shmid;
char *buffer;
pid_t pid1, pid2;
// 创建共享内存
shmid = shmget(SHM_KEY, BUFFER_SIZE, IPC_CREAT | 0666);
if (shmid < 0) {
perror("shmget error");
exit(1);
}
// 连接共享内存
buffer = shmat(shmid, NULL, 0);
if (buffer == (char *) -1) {
perror("shmat error");
exit(1);
}
// 创建子进程1
pid1 = fork();
if (pid1 < 0) {
perror("fork error");
exit(1);
} else if (pid1 == 0) {
// 子进程1,从键盘读取字符串并写入共享内存
while (1) {
printf("Input a string for P1: ");
fgets(buffer, BUFFER_SIZE, stdin);
printf("P1 sent %s", buffer);
sleep(1);
}
}
// 创建子进程2
pid2 = fork();
if (pid2 < 0) {
perror("fork error");
exit(1);
} else if (pid2 == 0) {
// 子进程2,从键盘读取字符串并写入共享内存
while (1) {
printf("Input a string for P2: ");
fgets(buffer, BUFFER_SIZE, stdin);
printf("P2 sent %s", buffer);
sleep(1);
}
}
// 父进程,从共享内存读取字符串并显示
while (1) {
if (strlen(buffer) > 0) {
if (strncmp(buffer, "exit", 4) == 0) {
break;
}
if (strncmp(buffer, "P1", 2) == 0) {
printf("P3 received %s", buffer + 2);
} else if (strncmp(buffer, "P2", 2) == 0) {
printf("P3 received %s", buffer + 2);
}
memset(buffer, 0, BUFFER_SIZE);
}
sleep(1);
}
// 删除共享内存
shmdt(buffer);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
```
运行程序后,输入字符串并回车即可向共享内存中写入数据,程序会自动检测并显示接收到的字符串。输入"exit"并回车可退出程序。
阅读全文