我如何告诉 wc 停止阅读?
我有一个程序,fork()
创建一个新进程,然后用我的文件描述符管道fd
覆盖该新进程的stdin
。在此过程中,我然后使用 execvp() 执行 wc,它应该从父级读取其输入。 然后,在父级中,我写入管道的写入端,写入完成后,关闭管道。
问题是 wc
仍然等待输入并且 des 不退出。
通常,我可以通过输入 CTRLD 来停止 wc
,但我似乎无法在 C/C++ 中发送该信号。
如何告诉 wc
停止阅读?
编辑:我确实遵循了 pipeline/fork/dup/exec 习惯用法(我认为这就是它的名字。)
流式传输与其他需要输入的程序一起工作,只是 wc
需要特殊的 EOF
来停止读取。
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\n";
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;
}
}
抱歉,如果代码看起来有点脱节。我必须把它从文件中拉出来。
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++.
How do I tell wc
to stop reading?
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\n";
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;
}
}
Sorry if the code seems a little disjointed. I had to pull it together from around the file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您关闭
stdout
时,wc
退出。wc
exits when you close thestdout
.