当前位置:实例文章 » JAVA Web实例» [文章]【进程7】 2.15 有名管道介绍及使用 2.16有名管道实现简单版聊天功能

【进程7】 2.15 有名管道介绍及使用 2.16有名管道实现简单版聊天功能

发布人:shili8 发布时间:2025-02-13 00:51 阅读次数:0

**进程7**

###2.15 有名管道介绍及使用在 Linux 中,管道是一种用于进程间通信的机制。有名管道是指一个特殊类型的管道,它允许多个进程同时访问同一个管道。

#### 有名管道的特点:

* 有名管道是一个文件描述符,通过 `mkfifo` 命令创建。
* 多个进程可以同时读写有名管道。
* 有名管道是阻塞式的,即如果没有数据可读或写入时,进程会被阻塞。

#### 使用有名管道的步骤:

1. 创建一个有名管道:使用 `mkfifo` 命令创建一个有名管道。
2. 打开有名管道:使用 `open` 系统调用打开有名管道,得到一个文件描述符。
3.读写数据:使用 `read` 和 `write` 系统调用的读取和写入数据。

###2.16 有名管道实现简单版聊天功能在这个例子中,我们将使用有名管道来实现一个简单的聊天功能。我们将创建两个进程,一个负责发送消息(Sender),另一个负责接收并显示消息(Receiver)。

#### Sender 程序:

c#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define FIFO_NAME "/tmp/chat_fifo"

int main() {
 int fd;
 char message[100];

 // 打开有名管道 if ((fd = open(FIFO_NAME, O_WRONLY)) == -1) {
 perror("open");
 exit(1);
 }

 printf("Sender: ");
 fgets(message,100, stdin);

 // 写入消息到有名管道 if (write(fd, message, strlen(message)) != strlen(message)) {
 perror("write");
 exit(1);
 }

 close(fd);
 return0;
}


#### Receiver 程序:

c#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define FIFO_NAME "/tmp/chat_fifo"

int main() {
 int fd;
 char message[100];

 // 打开有名管道 if ((fd = open(FIFO_NAME, O_RDONLY)) == -1) {
 perror("open");
 exit(1);
 }

 while (1) {
 //读取消息从有名管道 if (read(fd, message,100) <=0) {
 break;
 }

 printf("Receiver: %s", message);

 memset(message,0,100); // 清空缓冲区 }

 close(fd);
 return0;
}


#### 使用步骤:

1. 创建有名管道:使用 `mkfifo` 命令创建一个有名管道。
2. 运行 Sender 程序和 Receiver 程序。
3. 在 Sender 程序中输入消息,然后回车发送。
4. 在 Receiver 程序中会显示收到的消息。

通过这个例子,我们可以看到有名管道的使用非常简单,进程之间可以轻松地进行通信。

其他信息

其他资源

Top