简体   繁体   English

我怎么告诉wc停止阅读?

[英]How do I tell wc to stop reading?

I have a program that fork() sa new process and then overwrites that new process's stdin with my file descriptor pipe fd . 我有一个fork()是一个新进程的程序,然后使用我的文件描述符管道fd覆盖新进程的stdin In this process, I then use execvp() to execute wc and it should read its input from the parent. 在这个过程中,我然后使用execvp()来执行wc ,它应该从父级读取它的输入。 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. 问题是wc仍然期待输入而不会退出。
Usually, I can stop wc by typing CTRL D but I can't seem to send that signal in C/C++. 通常,我可以通过键入CTRL D来停止wc ,但我似乎无法在C / C ++中发送该信号。

How do I tell wc to stop reading? 我怎么告诉wc停止阅读?

EDIT : I did follow the pipe/fork/dup/exec idiom (I think that's what it's called.) 编辑 :我确实按照管道/ fork / dup / exec习惯用法(我认为这就是所谓的。)
The streaming works with other programs that need input, its just that wc needs the special EOF to stop reading. 流式传输与其他需要输入的程序一起工作,只是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;
    }
}

Sorry if the code seems a little disjointed. 对不起,如果代码似乎有点脱节。 I had to pull it together from around the file. 我不得不从文件周围将它拉到一起。

关闭stdout时, wc退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM