【问题标题】:sending and recieving text to/from child process向/从子进程发送和接收文本
【发布时间】:2021-11-06 21:35:47
【问题描述】:

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

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

在子进程分支中,我使用 dup2() 将 stdin 和 stdout 替换为 fd2 和 fd1,然后由 execlp 创建的 clang 格式进程将其作为 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);
  }
}

【问题讨论】:

  • clang-format 可能正在等待 EOF 读取。尝试在write之后关闭父进程中的fd2[1]
  • @kaylum 成功了,非常感谢!

标签: c pipe


【解决方案1】:

根据 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);
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多