MST

星途 面试题库

面试题:进程管理之管道机制中等难度题

在Linux系统中,使用管道机制实现两个进程间通信,父进程向子进程发送一段字符串,子进程接收并打印。请简述实现思路,并给出关键代码片段。
19.6万 热度难度
操作系统进程管理

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 使用 pipe 函数创建管道,该函数会创建一个包含两个文件描述符的数组,一个用于读(fd[0]),一个用于写(fd[1])。
  2. 使用 fork 函数创建子进程。
  3. 在父进程中关闭读端文件描述符(fd[0]),使用写端文件描述符(fd[1])向管道写入字符串。
  4. 在子进程中关闭写端文件描述符(fd[1]),使用读端文件描述符(fd[0])从管道读取字符串并打印。

关键代码片段

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define BUFFER_SIZE 1024

int main() {
    int pipe_fd[2];
    if (pipe(pipe_fd) == -1) {
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    pid_t pid = fork();
    if (pid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    } else if (pid == 0) {  // 子进程
        close(pipe_fd[1]);  // 关闭写端
        char buffer[BUFFER_SIZE];
        ssize_t bytes_read = read(pipe_fd[0], buffer, sizeof(buffer) - 1);
        if (bytes_read == -1) {
            perror("read");
            exit(EXIT_FAILURE);
        }
        buffer[bytes_read] = '\0';
        printf("子进程接收到: %s\n", buffer);
        close(pipe_fd[0]);  // 关闭读端
    } else {  // 父进程
        close(pipe_fd[0]);  // 关闭读端
        const char *message = "Hello, child process!";
        if (write(pipe_fd[1], message, strlen(message)) == -1) {
            perror("write");
            exit(EXIT_FAILURE);
        }
        close(pipe_fd[1]);  // 关闭写端
        wait(NULL);  // 等待子进程结束
    }

    return 0;
}