Domanda

void execute_command_pipe(char * command_from, char * command_to, char ** args_from, char ** args_to) {
    pipe(pipefd);

    int pid = fork();
    close(pipefd[0]);
    if (pid == 0) {
        //close(STDOUT_FILENO);
        dup2(pipefd[1], STDOUT_FILENO);
        int rv1 = execv(get_contain_dir(command_from), args_from);
        close(pipefd[1]);
    } else {
        close(pipefd[1]);
        dup2(pipefd[0], STDIN_FILENO);
        int rv2 = execv(get_contain_dir(command_to), args_to);
        close(pipefd[0]);
    }
}

for example, if I wanted to do the equivalent of ls | grep test, the parent thread would run grep listening for input on STDIN, and the child thread would write the output of ls to STDTOUT.

Nessuna soluzione corretta

Altri suggerimenti

Is using low-level pipe/fork is necessary? If no - more easy way - to use popen/pclose system calls.

For your example with ls | grep, this is:

FILE *f = popen("ls");
char buf[1000];
while(fgets(buf, sizeof(buf), f) 
  call_my_grep(buf);
pclose(f);

This is easy and efficient.

void execute_command_pipe(char * command_from, char * command_to, char ** args_from, char ** args_to) {
    pipe(pipefd);

    int pid = fork();
    if (pid != 0) {
        dup2(pipefd[0], STDIN_FILENO);
        close(pipefd[0]);
        int rv2 = execv(get_contain_dir(command_to), args_to);
    } else {
        dup2(pipefd[1], STDOUT_FILENO);
        close(pipefd[1]);
        int rv1 = execv(get_contain_dir(command_from), args_from);
        close(pipefd[0]);
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top