简体   繁体   中英

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 . 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 CTRL D 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.

关闭stdout时, wc退出。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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