简体   繁体   中英

Can't execute console commands in C with fork and pipe

I'm trying to make program on C, which execute console shell command

cat log.txt| awk '{ print $7 }' | head -10

but the third command won't work with 2 present. Here's what i done

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main() 
{
    int fd[2], status;

    pipe(fd);
    pid_t pid1 = fork();

    if (!pid1) 
    { 
        dup2(fd[1], 1);
        close(fd[0]);
        close(fd[1]);
        char* command[3] = {"/bin/cat", "log.txt", 0}; 
        execvp(command[0], command);
        exit(EXIT_FAILURE);
    } 
    else if (pid1 == -1) 
    {
        fprintf(stderr, "Can't fork, exiting...\n");
        exit(EXIT_FAILURE);
    }

    pid_t pid2 = fork();

    if (!pid2) {
            dup2(fd[0], 0);
            close(fd[0]);
            close(fd[1]);

            char* command[3] = {"awk", "{ print $7 }", 0}; 
            execvp(command[0], command);

            exit(EXIT_FAILURE);
    } else if (pid2 == -1) {
            fprintf(stderr, "Can't fork, exiting...\n"); 
            exit(EXIT_FAILURE);
    }

    pid_t pid3 = fork();

    if (!pid3) {
            dup2(fd[0], 0);
            close(fd[0]);
            close(fd[1]);

            char* command[3] = {"head", "-10", 0}; 
            execvp(command[0], command);

            exit(EXIT_FAILURE);
    } else if (pid3 == -1) {
            fprintf(stderr, "Can't fork, exiting...\n"); 
            exit(EXIT_FAILURE);   
    }

    close(fd[0]);
    close(fd[1]);

    waitpid(pid1, NULL, 0);
    waitpid(pid2, NULL, 0);
    waitpid(pid3, &status, 0);

    exit(status);

    return 0;
}

pid3 can't execute. I tried to make dup2(fd[1], 1) in pid3, but thats doesn't work. What should be on pid3 to make it's work and how to make more than 3 commands using dup2?

You will have to set up two pipes-- one to connect cat to awk and one to connect awk to head .

Also, don't close file descriptors that you actually need (such as fd[0] in your first fork!)

You have created one pipe. One pipe has two ends. Two ends are enough for two processes. If you have three processes all in a single pipeline, you need two pipes. The process in the middle holds on two pipes and two other processes hold on the remaining ends.

Look at this picture:

 cat | awk | head

See two pipe symbols? They are the two pipes you need.

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