MST

星途 面试题库

面试题:C语言中命名管道(FIFO)创建及简单读写操作

在C语言中,如何使用命名管道(FIFO)实现两个进程间的通信?请写出创建FIFO、打开FIFO进行读写操作的关键代码片段,并简要说明各个函数的作用。
44.6万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
  1. 创建FIFO
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main() {
    const char* fifo_name = "my_fifo";
    // 创建命名管道
    if (mkfifo(fifo_name, 0666) == -1) {
        perror("mkfifo");
        return 1;
    }
    return 0;
}
  • mkfifo函数:
    • 函数原型:int mkfifo(const char *pathname, mode_t mode);
    • 作用:创建一个命名管道(FIFO),pathname是要创建的FIFO的路径名,mode指定了FIFO的权限,如0666表示所有者、组和其他用户都有读和写的权限。如果创建成功返回0,否则返回 -1,并设置errno来指示错误原因。
  1. 打开FIFO进行读写操作(以读操作进程为例)
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

int main() {
    const char* fifo_name = "my_fifo";
    int fd;
    char buffer[1024];
    // 打开FIFO进行读操作
    fd = open(fifo_name, O_RDONLY);
    if (fd == -1) {
        perror("open");
        return 1;
    }
    // 从FIFO读取数据
    ssize_t bytes_read = read(fd, buffer, sizeof(buffer) - 1);
    if (bytes_read == -1) {
        perror("read");
        close(fd);
        return 1;
    }
    buffer[bytes_read] = '\0';
    printf("Read from FIFO: %s\n", buffer);
    close(fd);
    return 0;
}
  • open函数:
    • 函数原型:int open(const char *pathname, int flags);
    • 作用:打开一个文件或设备,在这里用于打开命名管道。pathname是FIFO的路径名,O_RDONLY表示以只读方式打开。如果打开成功返回文件描述符,否则返回 -1,并设置errno指示错误原因。
  • read函数:
    • 函数原型:ssize_t read(int fd, void *buf, size_t count);
    • 作用:从文件描述符fd对应的文件中读取数据到buf缓冲区,count指定最多读取的字节数。返回实际读取的字节数,如果出错返回 -1,并设置errno
  1. 打开FIFO进行读写操作(以写操作进程为例)
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

int main() {
    const char* fifo_name = "my_fifo";
    int fd;
    const char* message = "Hello, FIFO!";
    // 打开FIFO进行写操作
    fd = open(fifo_name, O_WRONLY);
    if (fd == -1) {
        perror("open");
        return 1;
    }
    // 向FIFO写入数据
    ssize_t bytes_written = write(fd, message, strlen(message));
    if (bytes_written == -1) {
        perror("write");
        close(fd);
        return 1;
    }
    close(fd);
    return 0;
}
  • write函数:
    • 函数原型:ssize_t write(int fd, const void *buf, size_t count);
    • 作用:向文件描述符fd对应的文件中写入数据,buf是要写入的数据缓冲区,count指定要写入的字节数。返回实际写入的字节数,如果出错返回 -1,并设置errno