linux2.设计两个程序:有名管道的读程序和写程序,要求利用有名管道实现聊天程序,每次发言后自动在后面增加当前系统时间。增加结束字符,比如最后输入“886”后结束进程。
时间: 2023-12-29 18:03:10 浏览: 29
下面分别给出有名管道的读程序和写程序的代码实现。
## 有名管道的写程序
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <fcntl.h>
#include <sys/stat.h>
#define FIFO_FILE "/tmp/chat_fifo"
int main()
{
int fd;
char buf[1024];
// 创建有名管道
mkfifo(FIFO_FILE, 0666);
// 打开有名管道
fd = open(FIFO_FILE, O_WRONLY);
// 循环读取用户输入并写入管道
while (1) {
printf("请输入您要发送的消息:");
scanf("%s", buf);
time_t t = time(NULL);
struct tm *tm = localtime(&t);
// 在消息后面加上当前系统时间
sprintf(buf + strlen(buf), " [%04d-%02d-%02d %02d:%02d:%02d]",
tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec);
// 写入有名管道
write(fd, buf, strlen(buf) + 1);
// 判断用户是否输入结束标志
if (strcmp(buf, "886") == 0) {
break;
}
}
// 关闭有名管道
close(fd);
// 删除有名管道
unlink(FIFO_FILE);
return 0;
}
```
## 有名管道的读程序
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#define FIFO_FILE "/tmp/chat_fifo"
int main()
{
int fd;
char buf[1024];
// 打开有名管道
fd = open(FIFO_FILE, O_RDONLY);
// 循环读取管道中的数据并输出
while (1) {
// 读取管道中的数据
read(fd, buf, 1024);
// 判断是否接收到结束标志
if (strcmp(buf, "886") == 0) {
break;
}
// 输出收到的消息
printf("收到消息:%s\n", buf);
}
// 关闭有名管道
close(fd);
return 0;
}
```
要使用以上两个程序进行聊天,需要先运行读程序,然后再运行写程序。写程序会在用户输入一条消息后将消息写入管道,读程序会不断读取管道中的数据并输出。用户可以在写程序中输入“886”来结束聊天。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)