c - 向/从子进程发送和接收文本
问题描述
我正在尝试将一些文本从父进程发送到子进程,子进程将处理文本,然后将其发送回父进程。下面是我到目前为止的代码,但是第 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);
}
}
解决方案
根据 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);
}
}
推荐阅读
- r - 如何防止 RMySQL 错误并在 Shiny 中向用户显示?
- angularjs - AngularJS $http 发布请求:[$http:baddata] 职位限制
- javascript - 使用不区分大小写的正则表达式从 JS 数组中过滤和删除项目
- python - 使用 Scikit Learn DecisionTreeClassifier 保存 Graphviz 决策树图
- sql-server - 为什么数据库有 100 万行时变得如此缓慢?
- java - 来自 sqoop.tool 的 ImportTool 不适用于参数 (org.apache.sqoop.SqoopOptions)
- php - 如何让我在 Heroku 上的 Laravel 项目使用 Heroku Postgres?
- c# - 为什么我的数据库在 ASP.NET Core 2.1 中播种后仍然是空的?
- audio - 立体声模拟音频源的“单声道”FFT 可视化
- node.js - http-only cookie + token:双重工作?