C语言实现FIFO算法,将这个项目编程三个例程,“发送者”、“接收者”和“路由器”。
时间: 2023-10-03 08:10:12 浏览: 41
下面是C语言实现FIFO算法的示例代码,包括发送者、接收者和路由器三个例程。
发送者(Sender):
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MAX_MSG_SIZE 512
struct msgbuf {
long mtype;
char mtext[MAX_MSG_SIZE];
};
int main(int argc, char **argv)
{
key_t key;
int msqid;
struct msgbuf msg;
int count = 0;
if (argc != 2) {
fprintf(stderr, "Usage: %s key\n", argv[0]);
exit(EXIT_FAILURE);
}
key = atoi(argv[1]);
msqid = msgget(key, IPC_CREAT | 0666);
if (msqid < 0) {
perror("msgget");
exit(EXIT_FAILURE);
}
while (1) {
sprintf(msg.mtext, "Message %d from sender", count++);
msg.mtype = 1;
if (msgsnd(msqid, &msg, strlen(msg.mtext)+1, 0) < 0) {
perror("msgsnd");
break;
}
printf("Sent message: %s\n", msg.mtext);
sleep(1);
}
msgctl(msqid, IPC_RMID, NULL);
return 0;
}
```
接收者(Receiver):
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MAX_MSG_SIZE 512
struct msgbuf {
long mtype;
char mtext[MAX_MSG_SIZE];
};
int main(int argc, char **argv)
{
key_t key;
int msqid;
struct msgbuf msg;
if (argc != 2) {
fprintf(stderr, "Usage: %s key\n", argv[0]);
exit(EXIT_FAILURE);
}
key = atoi(argv[1]);
msqid = msgget(key, IPC_CREAT | 0666);
if (msqid < 0) {
perror("msgget");
exit(EXIT_FAILURE);
}
while (1) {
if (msgrcv(msqid, &msg, MAX_MSG_SIZE, 1, 0) < 0) {
perror("msgrcv");
break;
}
printf("Received message: %s\n", msg.mtext);
}
msgctl(msqid, IPC_RMID, NULL);
return 0;
}
```
路由器(Router):
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MAX_MSG_SIZE 512
struct msgbuf {
long mtype;
char mtext[MAX_MSG_SIZE];
};
int main(int argc, char **argv)
{
key_t key;
int msqid[2];
struct msgbuf msg;
if (argc != 3) {
fprintf(stderr, "Usage: %s key1 key2\n", argv[0]);
exit(EXIT_FAILURE);
}
key = atoi(argv[1]);
msqid[0] = msgget(key, IPC_CREAT | 0666);
if (msqid[0] < 0) {
perror("msgget");
exit(EXIT_FAILURE);
}
key = atoi(argv[2]);
msqid[1] = msgget(key, IPC_CREAT | 0666);
if (msqid[1] < 0) {
perror("msgget");
exit(EXIT_FAILURE);
}
while (1) {
if (msgrcv(msqid[0], &msg, MAX_MSG_SIZE, 1, 0) < 0) {
perror("msgrcv");
break;
}
printf("Received message: %s\n", msg.mtext);
msg.mtype = 1;
if (msgsnd(msqid[1], &msg, strlen(msg.mtext)+1, 0) < 0) {
perror("msgsnd");
break;
}
printf("Sent message: %s\n", msg.mtext);
}
msgctl(msqid[0], IPC_RMID, NULL);
msgctl(msqid[1], IPC_RMID, NULL);
return 0;
}
```