Реализация PS Aux |больше в C - PullRequest
0 голосов
/ 17 октября 2019

Я хотел реализовать следующую команду ps aux |больше, чтобы лучше понять функционирование труб. Чтобы добиться этого, я написал следующий код:

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

int main(int argc, char** argv) {
    pid_t pid;
    int pipefd[2];

    //We first create the pipe
    if(pipe(pipefd) == -1) {
        fprintf(stderr, "Pipe failed\n");
        exit(EXIT_FAILURE);
    }

    //Now we create the child process
    if((pid = fork()) < 0) {
        fprintf(stderr, "Fork failed\n");
        exit(EXIT_FAILURE);
    }

    if(pid > 0) {
        //Parent process

        //We first close the read-end part of the pipe
        close(pipefd[0]);

        execl("/bin/ps", "/bin/ps", "aux", (char *) NULL);

        wait(NULL);   

        exit(EXIT_SUCCESS);
    } else {
        //Child process

        //For the son, we close the writing end part of the pipe
        close(pipefd[1]);

        //We then define that all the standard inputs will go to the read-end part of the pipe
        dup2(pipefd[0], 0);
        close(pipefd[0]);

        execl("/bin/more", "/bin/more", (char  *) NULL);    

        exit(EXIT_SUCCESS);
    }
}

Мне удалось увидеть активные процессы на консоли, но они не разбиты на страницы. Похоже, команда больше не была выполнена. Есть ли кто-нибудь, кто мог бы помочь мне в этом?

Заранее спасибо.

...