Linux 有P1,P2,P3三个进程,P1和P2负责从键盘接收字符串,均发送给P3,P3接收字符串,根据消息的发送方分别显示“received from p1""received from p2”,分别用消息队列和共享存储的方式实现,形成可运行的代码
时间: 2023-11-22 08:55:56 浏览: 35
使用消息队列:
P1代码:
```c
#include <stdio.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct msgbuf {
long mtype;
char mtext[256];
};
int main() {
key_t key = ftok(".", 'a');
int msqid = msgget(key, IPC_CREAT | 0666);
struct msgbuf msg;
while(1) {
printf("Enter a string: ");
fgets(msg.mtext, 256, stdin);
msg.mtype = 1;
msgsnd(msqid, &msg, strlen(msg.mtext)+1, 0);
}
return 0;
}
```
P2代码:
```c
#include <stdio.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct msgbuf {
long mtype;
char mtext[256];
};
int main() {
key_t key = ftok(".", 'a');
int msqid = msgget(key, IPC_CREAT | 0666);
struct msgbuf msg;
while(1) {
printf("Enter a string: ");
fgets(msg.mtext, 256, stdin);
msg.mtype = 2;
msgsnd(msqid, &msg, strlen(msg.mtext)+1, 0);
}
return 0;
}
```
P3代码:
```c
#include <stdio.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct msgbuf {
long mtype;
char mtext[256];
};
int main() {
key_t key = ftok(".", 'a');
int msqid = msgget(key, IPC_CREAT | 0666);
struct msgbuf msg;
while(1) {
msgrcv(msqid, &msg, 256, 0, 0);
if(msg.mtype == 1) {
printf("received from p1: %s", msg.mtext);
} else if(msg.mtype == 2) {
printf("received from p2: %s", msg.mtext);
}
}
return 0;
}
```
使用共享内存:
P1代码:
```c
#include <stdio.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main() {
key_t key = ftok(".", 'a');
int shmid = shmget(key, 256, IPC_CREAT | 0666);
char *shmaddr = shmat(shmid, NULL, 0);
while(1) {
printf("Enter a string: ");
fgets(shmaddr, 256, stdin);
*shmaddr = '1';
}
return 0;
}
```
P2代码:
```c
#include <stdio.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main() {
key_t key = ftok(".", 'a');
int shmid = shmget(key, 256, IPC_CREAT | 0666);
char *shmaddr = shmat(shmid, NULL, 0);
while(1) {
printf("Enter a string: ");
fgets(shmaddr, 256, stdin);
*shmaddr = '2';
}
return 0;
}
```
P3代码:
```c
#include <stdio.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main() {
key_t key = ftok(".", 'a');
int shmid = shmget(key, 256, IPC_CREAT | 0666);
char *shmaddr = shmat(shmid, NULL, 0);
while(1) {
if(*shmaddr == '1') {
printf("received from p1: %s", shmaddr+1);
*shmaddr = '0';
} else if(*shmaddr == '2') {
printf("received from p2: %s", shmaddr+1);
*shmaddr = '0';
}
}
return 0;
}
```