linux设计两个程序:有名管道的读程序和写程序,要求利用有名管道实现聊天程序,每次发言后自动在后面增加当前系统时间。增加结束字符,比如最后输入“886”后结束进程。
时间: 2023-12-18 11:05:26 浏览: 27
以下是有名管道的读程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#define MAX_BUF_SIZE 1024
int main()
{
int fd;
char *fifo_name = "/tmp/chat_fifo";
char buf[MAX_BUF_SIZE];
// 创建有名管道
mkfifo(fifo_name, 0666);
// 打开管道并读取数据
fd = open(fifo_name, O_RDONLY);
while (1) {
read(fd, buf, MAX_BUF_SIZE);
if (strcmp(buf, "886") == 0) {
break;
}
time_t now;
time(&now);
printf("[%s] %s\n", ctime(&now), buf);
}
// 关闭管道并删除有名管道文件
close(fd);
unlink(fifo_name);
return 0;
}
```
以下是有名管道的写程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#define MAX_BUF_SIZE 1024
int main()
{
int fd;
char *fifo_name = "/tmp/chat_fifo";
char buf[MAX_BUF_SIZE];
// 打开管道并写入数据
fd = open(fifo_name, O_WRONLY);
while (1) {
fgets(buf, MAX_BUF_SIZE, stdin);
time_t now;
time(&now);
printf("[%s] %s\n", ctime(&now), buf);
write(fd, buf, strlen(buf) + 1);
if (strcmp(buf, "886\n") == 0) {
break;
}
}
// 关闭管道
close(fd);
return 0;
}
```
使用方法:
1. 分别编译上面的读程序和写程序:`gcc chat_read.c -o chat_read` 和 `gcc chat_write.c -o chat_write`
2. 打开两个终端,分别进入编译好的可执行文件所在目录
3. 在一个终端中运行读程序:`./chat_read`
4. 在另一个终端中运行写程序:`./chat_write`
5. 两个终端即可开始聊天,输入"886"结束聊天。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![apk](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)