I have a program that fork()
s a new process and then overwrites that new process s stdin
with my file descriptor pipe fd
. In this process, I then use execvp()
to execute wc
and it should read its input from the parent.
In the parent, I then write to the write end of the pipe and when done writing, close the pipe.
The problem is that wc
is still expecting input and des not exit.
Usually, I can stop wc
by typing CTRLD but I can t seem to send that signal in C/C++.
我如何告诉<代码>wc以停止阅读?
EDIT: I did follow the pipe/fork/dup/exec idiom (I think that s what it s called.)
The streaming works with other programs that need input, its just that wc
needs the special EOF
to stop reading.
int in_fd[2];
//parent-child setup
pipe(in_fd);
child = fork();
if(child == 0) {
close(in_fd[1]);
dup2(in_fd[0], 0);
close(in_fd[0]);
execvp(cmdArg[0], cmdArg);
} else {
close(in_fd[0]);
in_pid = fork_in_proc();
close(in_fd[1]);
}
//writing function
pid_t fork_in_proc() {
string line;
pid_t in_pid;
if((in_pid = fork()) == 0) {
close(in_fd[0]);
ifstream file(stream_file[STREAM_IN].c_str(), ios_base::in);
if (file.bad()) {
cerr << "File read error
";
return 1;
}
while(file.good()) {
getline(file, line);
if(file.good()) {
write(in_fd[1], line.c_str(), line.length());
}
}
int end = 3;
write(in_fd[1], &end, sizeof(end));
file.close();
close(in_fd[1]);
cout << "PIPE IN" << endl;
exit(0);
} else {
return in_pid;
}
}
如果该法典似乎有些脱节,则会发生争执。 我不得不从档案中集中起来。