写入错误:使用execlp的C语言中的管道损坏

I have issues creating simple C program which takes arguments from command line, the last argument is path to the file. Program runs cat command on given file, and then runs tr on the result of cat. Tr gets arguments from command line(other than the last argument). I am getting errors: Missing operand. write error: Broken Pipe. I am not sure where the mistake is...

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[]){
    if(argc < 2){
        printf("\nPROVIDE AN ARGUMENT\n");
        return 1;
    }
    const char * file = argv[argc - 1];
    const char * args = calloc(argc - 2, sizeof(char*));
    memcpy(args, argv, argc -2);

    int fd[2];
    pipe(fd);
    pid_t child;

    if((child = fork()) == -1)return 2;

    if(child == 0){
        close(fd[0]);
        close(STDOUT_FILENO);
        dup(fd[1]);
        close(fd[1]);
        execlp("cat", file, (char*)NULL);
        perror("execvp of ls failed");
        exit(0);
    }
    else{
        close(fd[1]);          
        close(STDIN_FILENO);   
        dup(fd[0]);            
        execlp("tr", args, (char*)NULL);
        close(fd[0]); 
        exit(0);
    }

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

    return 0;
}
评论