C pipes, stdin / stdout and sort

I am trying to write a program that forks and sends sort (linux) a few words to sort by stdin, since sorting without args will use stdin. Then assemble the stdout from the sort in the parent to output to the parent stdout.

My program is currently freezing. Can someone help me explain what is going wrong?

My code is:

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>


int main(int argc, char *argv[]){
    int fi[2];
    int fo[2];
    int oldstdin;
    int oldstdout;

    if (pipe(fi) == -1){
        exit(EXIT_FAILURE);
    }
    if (pipe(fo) == -1){
        exit(EXIT_FAILURE);
    }
    oldstdin = dup(STDIN_FILENO); /* Save current sdtin */
    oldstdout = dup(STDOUT_FILENO); /* Save current stdout */

    close(STDIN_FILENO);
    close(STDOUT_FILENO);


    if(dup2 (fo[0],STDIN_FILENO) == -1) /* Make the read end of out to be stdin */
        exit(EXIT_FAILURE);
    if(dup2 (fi[1],STDOUT_FILENO) == -1) /* Make the write end of in to be stdout */
        exit(EXIT_FAILURE);


    switch(fork()){
    case -1:
        exit(EXIT_FAILURE);
    case 0: /* CHILD */  
        close(fo[0]);
        close(fo[1]);
        close(fi[0]);
        close(fi[1]);
        execlp("sort","sort", (char *)NULL);
    default:
        break; /* fall through to parent */
    }

    char input[100];
    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    dup2(oldstdin,STDIN_FILENO);
    dup2(oldstdout,STDOUT_FILENO);

    close(fo[0]); /* these are used by CHILD */
    close(fi[1]); /* "" */

    write(fo[1],"dino\nbat\nfish\nzilla\nlizard\0",27);
    input[read(fi[0], input,100)] = 0;
    printf("%s", input);
}
+5
source share
1 answer

I do not think that sorting expects to stdinbe nul-terminated: it will not be redirected from the file.

, ( - , , ). fo[1] .

, strace -f, , , , , .

+1

All Articles