【发布时间】:2023-03-10 18:10:02
【问题描述】:
我正在尝试创建一个调用某个程序或进程的子进程。父级通过两个管道从子级写入和读取一些数据。我的代码编译并运行,但输入中没有文本。我究竟做错了什么?我是不是没有正确关闭管道、写入管道或正确输出数据?
#include <iostream>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
int main(){
int pipedes1[2],pipedes2[2];
char buff[256];
string text = "Hello";
pid_t pid;
pipe(pipedes1);
pipe(pipedes2);
pid = fork();
if(pid > 0){
close(pipedes1[1]);
close(pipedes2[0]);
dup2(pipedes2[1], STDOUT_FILENO);
dup2(pipedes1[0], STDIN_FILENO);
execve("/home/pi/Test", NULL, NULL);
} else {
close(pipedes1[1]);
close(pipedes2[1]);
write(pipedes1[0], text.c_str(), text.length());
while((len = read(pipedes2[0], buff, 256)) != 0){
cout << buff << endl;
}
close(pipedes2[0]);
close(pipedes1[0]);
}
return 0;
}
还有我的“孩子”程序:
int main(){
string str;
cin >> str;
str = "echo " + str + " >> /home/pi/1";
cout << str << endl;
return 0;
}
程序的输出:
回声
我发现一个问题 write() 返回 -1。 但是不知道为什么?
【问题讨论】:
标签: c++ subprocess pipe fork