简体   繁体   中英

dup2, pipe and fork in C

I'm supposed to implement a program that will simulate the behavior of "ls -l | sort -n", I've written my code and according to my logic everything should work perfectly, but it does not. I've been trying to debug this for the last few hours so any additional input would be much appreciated. Here's the code:

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

int main(int argc, char *argv[])
{
    int fd[2];
    int errcheck;
    errcheck = pipe(fd);
    printf("Errcheck after pipe call: %d\n", errcheck);
    pid_t childpid;
    childpid=fork();
    if(childpid==0)
    {
        printf("Entering child\n");
        errcheck = dup2(fd[1], STDOUT_FILENO);
        printf("Errcheck after dup2 child: %d\n", errcheck);
        close(fd[0]);
        execl("bin/ls", "ls", "-l", NULL);
    }
    printf("Before sort call\n");
    errcheck = dup2(fd[0], STDIN_FILENO);
    printf("Errcheck after dup2 parent: %d\n", errcheck);
    close(fd[1]);
    execl("/usr/bin/sort", "sort", "-n", NULL);
}

The program gets stuck after "Entering child", I really don't understand why the child dup2 call doesn't complete...

Thank you in advance for any help.

Is there a reason not to use dirent to list the files - opendir readdir and so on? Or is this a school assignment? If it is meant for production consider using dirent.h and stat.h.

For schoolwork it is up to your prof what you need to do. Please label this as homework if that is the case.

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