我使用4个进程,其中A的输出将转到A1,A1的输出将转到A2,A2的输出将在控制台中显示。就连A1的输出也会出现在控制台上。
stdout的收集器-- Python脚本将接受A的输出并根据A2的要求生成输出,A1的输出应在控制台中打印。我使用两个管道- ABtoC表示A到A1,A1toA2表示A1toA2。
这里A到A1正在工作,A1的输出在控制台中打印。但问题是A1的输出不会流向A2的输入。下面是我在这个操作中使用的代码。
#include <vector>
#include <iostream>
#include <signal.h>
#include <unistd.h>
#include <string>
#include <sstream>
/// Entry point of process B
int procB(void) {
// Process B writing to C
while (!std::cin.eof()) {
// read a line of input until EOL and store in a string
std::string line;
std::getline(std::cin, line);
if (line.size() > 0)
std::cout << line << std::endl;
}
std::cout << std::endl;
return 0;
}
int main(int argc, char** argv) {
std::vector<pid_t> kids;
// create a pipe
int ABtoC[2];
pipe(ABtoC);
int A1toA2[2];
pipe(A1toA2);
pid_t child_pid;
child_pid = fork();
if (child_pid == 0) {
// redirect stdout to the pipe
dup2(ABtoC[1], STDOUT_FILENO);
close(ABtoC[0]);
close(ABtoC[1]);
close(A1toA2[0]);
close(A1toA2[1]); // Close this too!
execv("./rgen", argv);
} else if (child_pid < 0) {
std::cerr << "Error: could not fork\n";
return 1;
}
kids.push_back(child_pid);
child_pid = fork();
if (child_pid == 0) {
// redirect stdin from the pipe
dup2(ABtoC[0], STDIN_FILENO);
close(ABtoC[1]);
close(ABtoC[0]);
close(A1toA2[0]);
close(A1toA2[1]);
argv[0] = (char *)"python3";
argv[1] = (char *)"a1ece650.py";
argv[2] = nullptr;
dup2(A1toA2[1], STDOUT_FILENO);
close(A1toA2[1]);
close(A1toA2[0]);
close(ABtoC[0]);
close(ABtoC[1]);
execvp("python3", argv);
} else if (child_pid < 0) {
std::cerr << "Error: could not fork\n";
return 1;
}
kids.push_back(child_pid);
child_pid = fork();
if (child_pid == 0) {
// redirect stdin from the pipe
dup2(A1toA2[0], STDIN_FILENO);
close(A1toA2[1]);
close(A1toA2[0]);
close(ABtoC[0]);
close(ABtoC[1]);
execv("./ece650-a2", argv);
} else if (child_pid < 0) {
std::cerr << "Error: could not fork\n";
return 1;
}
kids.push_back(child_pid);
child_pid = 0;
// redirect stdout to the pipe
dup2(A1toA2[1], STDOUT_FILENO);
close(A1toA2[0]);
close(A1toA2[1]);
close(ABtoC[0]);
close(ABtoC[1]);
// start process B
int res = procB();
// send kill signal to all children
for (pid_t k : kids) {
int status;
kill(k, SIGTERM);
waitpid(k, &status, 0);
}
return res;
}插入ASCII图形如下:
+--------------+ +-----+ +-----+ +-----+
|Fork and Pipe| -- A.cpp stdout--stdin A1.py --stdout--stdin A2.cpp
+--------------+. +-----+ +-----+ +-----+
``` | | V V stdout stdout发布于 2021-03-20 04:34:57
当您启动A1时,您将关闭A1toA2[1],然后尝试将其放入stdout。首先完成所有的dup,然后关闭您不需要的内容。
https://stackoverflow.com/questions/66718213
复制相似问题