You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言结合fork与pipe实现管道读写拼接两个字符串的问题

问题根因

  • 父进程创建第一个子进程后未等待其完成输入,直接执行后续逻辑打印第二个输入提示,导致两个提示同时输出
  • 缺少父进程从管道读取两个字符串、拼接输出的完整逻辑
  • 部分文件描述符关闭逻辑不严谨,未处理读取长度容易出现冗余垃圾字符

改进后完整代码

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>

int main()
{
    int fd1[2], fd2[2];
    int status, pid;
    char buf1[100] = {0}, buf2[100] = {0};

    // 处理第一个字符串输入
    pipe(fd1);
    write(1, "String 1: \n", 11);
    pid = fork();
    if(pid == 0) /* 子进程1:读取第一个字符串写入管道1 */
    {
        close(fd1[0]);
        char cad1[100] = {0};
        int len = read(0, cad1, 99);
        write(fd1[1], cad1, len);
        close(fd1[1]);
        exit(0);
    }
    /* 父进程等待子进程1完成输入,保证顺序执行 */
    wait(&status);
    close(fd1[1]);
    // 从管道1读取第一个字符串
    read(fd1[0], buf1, 99);
    close(fd1[0]);
    // 去掉输入末尾的换行符
    buf1[strcspn(buf1, "\n")] = 0;

    // 处理第二个字符串输入
    pipe(fd2);
    write(1, "String 2: \n", 11);
    pid = fork();
    if(pid == 0) /* 子进程2:读取第二个字符串写入管道2 */
    {
        close(fd2[0]);
        char cad2[100] = {0};
        int len = read(0, cad2, 99);
        write(fd2[1], cad2, len);
        close(fd2[1]);
        exit(0);
    }
    /* 父进程等待子进程2完成输入 */
    wait(&status);
    close(fd2[1]);
    // 从管道2读取第二个字符串
    read(fd2[0], buf2, 99);
    close(fd2[0]);
    buf2[strcspn(buf2, "\n")] = 0;

    // 拼接输出
    strcat(buf1, buf2);
    write(1, "String cat:\n", 12);
    write(1, buf1, strlen(buf1));
    write(1, "\n", 1);

    return 0;
}

关键修改说明

  • 调整执行顺序:父进程创建第一个子进程后先调用wait()等待其输入完成,再打印第二个输入提示,避免两个提示同时输出
  • 补全了父进程从两个管道读取字符串、处理换行符、拼接输出的逻辑
  • 所有输入输出都使用read()/write()实现,符合要求
  • 记录读取长度、初始化字符数组,避免出现冗余垃圾字符
  • 补充了所有必要的头文件,完善文件描述符关闭逻辑,避免资源泄漏

内容的提问来源于stack exchange,提问作者Jorge Pulido Lozano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 10:06:02