MST

星途 面试题库

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

在Linux环境下,使用C语言编写一个简单的命名管道跨进程通信示例,要求创建一个命名管道,一个进程往管道里写入字符串'Hello, Pipe!',另一个进程从管道中读取并打印该字符串。请写出关键代码并说明可能出现的错误及处理方法。
49.5万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试

关键代码

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

#define FIFO_NAME "myfifo"
#define BUFFER_SIZE 100

int main() {
    // 创建命名管道
    int mkfifo_status = mkfifo(FIFO_NAME, 0666);
    if (mkfifo_status == -1 && errno != EEXIST) {
        perror("mkfifo");
        return 1;
    }

    // 创建子进程
    pid_t pid = fork();
    if (pid == -1) {
        perror("fork");
        return 1;
    } else if (pid == 0) {
        // 子进程 - 写管道
        int fd = open(FIFO_NAME, O_WRONLY);
        if (fd == -1) {
            perror("open for writing");
            return 1;
        }
        const char *message = "Hello, Pipe!";
        ssize_t write_status = write(fd, message, strlen(message) + 1);
        if (write_status == -1) {
            perror("write");
        }
        close(fd);
    } else {
        // 父进程 - 读管道
        int fd = open(FIFO_NAME, O_RDONLY);
        if (fd == -1) {
            perror("open for reading");
            return 1;
        }
        char buffer[BUFFER_SIZE];
        ssize_t read_status = read(fd, buffer, BUFFER_SIZE);
        if (read_status == -1) {
            perror("read");
        } else {
            printf("Read from pipe: %s\n", buffer);
        }
        close(fd);
        wait(NULL);
        unlink(FIFO_NAME);
    }

    return 0;
}

可能出现的错误及处理方法

  1. mkfifo失败:如果mkfifo函数调用失败,且errno不是EEXIST(表示管道已存在),则说明创建命名管道出错。可以通过perror函数打印错误信息,然后退出程序。
  2. fork失败fork函数用于创建子进程,如果失败,通过perror打印错误信息并退出程序。
  3. open失败:无论是以写模式还是读模式打开命名管道,如果open函数调用失败,通过perror打印错误信息并退出程序。写模式打开失败可能是因为管道不存在或者权限问题;读模式打开失败可能是因为管道未创建或者权限不足。
  4. write失败:在向管道写入数据时,如果write函数调用失败,通过perror打印错误信息。这可能是因为管道的另一端未打开,或者磁盘已满等原因。
  5. read失败:从管道读取数据时,如果read函数调用失败,通过perror打印错误信息。可能是因为管道未正确写入数据,或者管道已关闭等原因。