簡體   English   中英

dup2,C中的管道和叉子

[英]dup2, pipe and fork in C

我應該實現一個可以模擬“ ls -l | sort -n”行為的程序,我已經編寫了代碼,根據我的邏輯,一切都應該正常工作,但事實並非如此。 在過去的幾個小時中,我一直在嘗試對此進行調試,因此非常感謝任何其他輸入。 這是代碼:

#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);
}

該程序在“進入孩子”之后卡住,我真的不明白為什么孩子dup2調用未完成...

預先感謝您的任何幫助。

是否有理由不使用Dirent列出文件opendir readdir等等? 還是這是學校作業? 如果要用於生產,請考慮使用dirent.h和stat.h。

對於功課,您需要由教授決定。 如果是這種情況,請將其標記為作業。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM