MST

星途 面试题库

面试题:C语言中命名管道创建及基本通信

在Linux环境下,使用C语言创建一个命名管道,并实现一个简单的客户端 - 服务器模型的通信。客户端向命名管道写入一条字符串消息,服务器从命名管道读取该消息并打印出来。请写出主要的代码逻辑及关键函数的使用。
48.7万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试

服务器端代码逻辑

  1. 创建命名管道:使用 mkfifo 函数创建命名管道,函数原型为 int mkfifo(const char *pathname, mode_t mode);pathname 是命名管道的路径名,mode 是管道的权限。
  2. 打开命名管道:使用 open 函数以读模式打开命名管道,int open(const char *pathname, int flags);pathname 是管道路径,flags 设为 O_RDONLY
  3. 读取消息:使用 read 函数从管道读取数据,ssize_t read(int fd, void *buf, size_t count);fd 是管道文件描述符,buf 是存储读取数据的缓冲区,count 是最多读取的字节数。
  4. 打印消息:使用 printf 函数将读取到的消息打印出来。
  5. 关闭管道:使用 close 函数关闭管道,int close(int fd);fd 是管道文件描述符。

客户端代码逻辑

  1. 打开命名管道:使用 open 函数以写模式打开命名管道,flags 设为 O_WRONLY
  2. 写入消息:使用 write 函数向管道写入数据,ssize_t write(int fd, const void *buf, size_t count);fd 是管道文件描述符,buf 是要写入的缓冲区,count 是要写入的字节数。
  3. 关闭管道:使用 close 函数关闭管道。

示例代码

服务器端代码

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

#define FIFO_NAME "myfifo"

int main() {
    int fd;
    char buf[256];

    // 创建命名管道
    if (mkfifo(FIFO_NAME, 0666) == -1) {
        perror("mkfifo");
        exit(EXIT_FAILURE);
    }

    // 打开命名管道以读模式
    fd = open(FIFO_NAME, O_RDONLY);
    if (fd == -1) {
        perror("open");
        exit(EXIT_FAILURE);
    }

    // 从管道读取消息
    if (read(fd, buf, sizeof(buf)) == -1) {
        perror("read");
        exit(EXIT_FAILURE);
    }
    printf("Received message: %s\n", buf);

    // 关闭管道
    if (close(fd) == -1) {
        perror("close");
        exit(EXIT_FAILURE);
    }

    // 删除命名管道
    if (unlink(FIFO_NAME) == -1) {
        perror("unlink");
        exit(EXIT_FAILURE);
    }

    return 0;
}

客户端代码

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

#define FIFO_NAME "myfifo"

int main() {
    int fd;
    const char *msg = "Hello, server!";

    // 打开命名管道以写模式
    fd = open(FIFO_NAME, O_WRONLY);
    if (fd == -1) {
        perror("open");
        exit(EXIT_FAILURE);
    }

    // 向管道写入消息
    if (write(fd, msg, strlen(msg) + 1) == -1) {
        perror("write");
        exit(EXIT_FAILURE);
    }

    // 关闭管道
    if (close(fd) == -1) {
        perror("close");
        exit(EXIT_FAILURE);
    }

    return 0;
}