设计两个程序:有名管道的读程序和写程序,要求利用有名管道实现聊天程序,每次发言后自动在后面增加当前系统时间。增加结束字符,比如最后输入“886”后结束进程。
时间: 2023-12-18 11:05:25 浏览: 22
下面是使用有名管道实现聊天程序的读程序和写程序代码:
读程序代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#define FIFO_NAME "/tmp/chat_fifo"
int main()
{
int fd;
char message[100];
time_t cur_time;
// 创建有名管道
if (access(FIFO_NAME, F_OK) == -1)
{
if (mkfifo(FIFO_NAME, 0666) != 0)
{
fprintf(stderr, "Could not create fifo %s\n", FIFO_NAME);
exit(EXIT_FAILURE);
}
}
// 打开有名管道
fd = open(FIFO_NAME, O_RDONLY);
if (fd == -1)
{
fprintf(stderr, "Could not open fifo %s\n", FIFO_NAME);
exit(EXIT_FAILURE);
}
printf("Chat program started. Type '886' to exit.\n");
// 读取用户输入并写入有名管道
while (1)
{
memset(message, 0, sizeof(message)); // 清空message数组
read(fd, message, sizeof(message));
// 打印当前时间
time(&cur_time);
printf("%s: %s", ctime(&cur_time), message);
// 判断用户是否输入退出命令
if (strncmp(message, "886", 3) == 0)
{
break;
}
}
// 关闭有名管道文件描述符并删除有名管道
close(fd);
unlink(FIFO_NAME);
return 0;
}
```
写程序代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#define FIFO_NAME "/tmp/chat_fifo"
int main()
{
int fd;
char message[100];
time_t cur_time;
// 创建有名管道
if (access(FIFO_NAME, F_OK) == -1)
{
if (mkfifo(FIFO_NAME, 0666) != 0)
{
fprintf(stderr, "Could not create fifo %s\n", FIFO_NAME);
exit(EXIT_FAILURE);
}
}
// 打开有名管道
fd = open(FIFO_NAME, O_WRONLY);
if (fd == -1)
{
fprintf(stderr, "Could not open fifo %s\n", FIFO_NAME);
exit(EXIT_FAILURE);
}
printf("Chat program started. Type '886' to exit.\n");
// 读取用户输入并写入有名管道
while (1)
{
memset(message, 0, sizeof(message)); // 清空message数组
fgets(message, sizeof(message), stdin);
// 打印当前时间
time(&cur_time);
printf("%s: %s", ctime(&cur_time), message);
// 写入有名管道
write(fd, message, strlen(message));
// 判断用户是否输入退出命令
if (strncmp(message, "886", 3) == 0)
{
break;
}
}
// 关闭有名管道文件描述符并删除有名管道
close(fd);
unlink(FIFO_NAME);
return 0;
}
```
使用方法:
1. 打开终端,编译读程序和写程序:
```bash
gcc read.c -o read
gcc write.c -o write
```
2. 分别在两个终端中运行读程序和写程序:
终端1:
```bash
./read
```
终端2:
```bash
./write
```
3. 在写程序的终端中输入聊天内容,聊天内容将会显示在读程序的终端中,并且自动添加当前系统时间。当输入“886”后,聊天程序将会结束。