Linux通信机制 作业

要求

  1. 程序 1 从串口读取信息,然后发到消息队列中。使用 2 个终端运行程序 1,创建出 2 个可从串口读取数据的进程,串口可以使用 Windows 中的虚拟串口,使用串口助手输入信息。
  2. 程序 2 从消息队列中读取消息,然后在屏幕上将消息内容显示出来。

提交形式

  1. 代码
  2. 运行结果截图、串口助手截图

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>

#define BUFFER_SIZE 512

typedef struct _message {
long msg_type;
char msg_text[BUFFER_SIZE];
} message;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include "common.h"

int main() {
int qid;
key_t key;
message msg;

key = ftok(".", 'a');

qid = msgget(key, IPC_CREAT | 0666);

do {
memset(msg.msg_text, 0, BUFFER_SIZE);
msgrcv(qid, (void*)&msg, BUFFER_SIZE, 0, 0);

printf("%s", msg.msg_text);
} while (1);

msgctl(qid, IPC_RMID, NULL);

exit(0);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include "common.h"

int main() {
int qid, fd;
key_t key;
message msg;
char buff[BUFFER_SIZE];

key = ftok(".", 'a');
if (key == -1) {
perror("ftok error");
exit(1);
}

qid = msgget(key, IPC_CREAT | 0666);
if (qid == -1) {
perror("msgget error.");
exit(1);
}

fd = open("/dev/ttyS1", O_RDWR);
if (fd == -1) {
perror("open error.");
exit(1);
}

read(fd, buff, BUFFER_SIZE);
strncpy(msg.msg_text, buff, strlen(buff));
msg.msg_type = getpid();

int size = msgsnd(qid, &msg, strlen(msg.msg_text), 0);
if (size < 0) {
perror("message posted.");
exit(1);
}

exit(0);
}