首页 > 解决方案 > 向/从子进程发送和接收文本

问题描述

我正在尝试将一些文本从父进程发送到子进程,子进程将处理文本,然后将其发送回父进程。下面是我到目前为止的代码,但是第 30 行的 read() 调用挂起,我不知道如何调试它。

fd2管道供父进程写入代码字符串,以及供读取的 clang 格式(子)进程。管道用于写入的 clang 格式(子)进程和读取的父进程
fd

在子进程分支中,我使用 dup2() 将 stdin 和 stdout 替换为 fd2 和 fd1,然后由 execlp 创建的 clang-format 进程将其作为 stdin 和 stdout 继承。
在父进程分支中,我编写了 clang-format 的代码字符串来处理fd2[1],并从fd[0].

但是,read() 调用挂起。我究竟做错了什么?

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

int main() {
  int fd[2];
  int fd2[2];
  pid_t childPid;
  pipe(fd);
  pipe(fd2);
  if ((childPid = fork()) == -1) {
    perror("fork");
    exit(1);
  }
  if (childPid == 0) {
    dup2(fd[1], 1);
    close(fd[0]);
    dup2(fd2[0], 0);
    close(fd2[1]);
    execlp("clang-format", "clang-format", (char *)NULL);
  } else {
    close(fd[1]);
    close(fd2[0]);
    char code[] = "void\n cool\n(int num){return num +1;}\n";
    size_t codeLen = strlen(code);
    write(fd2[1], code, codeLen);
    char buf[401];
    ssize_t msgLen = read(fd[0], buf, 400);
    buf[msgLen] = '\0';
    printf("message from child: %s :end of message.\n", buf);
  }
}

标签: cpipe

解决方案


根据 kaylum 的评论,我需要close(fd2[1])在写信后这样做。所以完整的代码是:

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

int main() {
  int fd[2];
  int fd2[2];
  pid_t childPid;
  pipe(fd);
  pipe(fd2);
  if ((childPid = fork()) == -1) {
    perror("fork");
    exit(1);
  }
  if (childPid == 0) {
    dup2(fd[1], 1);
    close(fd[0]);
    dup2(fd2[0], 0);
    close(fd2[1]);
    execlp("clang-format", "clang-format", (char *)NULL);
  } else {
    close(fd[1]);
    close(fd2[0]);
    char code[] = "void\n cool\n(int num){return num +1;}\n";
    size_t codeLen = strlen(code);
    write(fd2[1], code, codeLen);
    close(fd2[1]);
    char buf[401];
    ssize_t msgLen = read(fd[0], buf, 400);
    buf[msgLen] = '\0';
    printf("message from child: %s :end of message.\n", buf);
  }
}

推荐阅读