簡體   English   中英

C:`write error:fork,dup2和execv之后的錯誤文件描述符`

[英]C: `write error: Bad file descriptor` after fork, dup2, and execv

繼續討論這個問題 ,但我會重申:

對於家庭作業,我必須編寫一個包括重定向的基本shell。 該程序使用readline來提示輸入,解析輸入字符串,並將其分解為可執行文件名,參數和輸入/輸出文件(如果適用)。 在解析字符串之后,它將forx和子execv()傳遞給傳入的可執行文件。我使用dup2()在fork之后和execv之前更改文件描述符,但是一旦遇到問題我就會遇到問題程序已執行新的可執行文件。 如果在我的shell中運行ls > foo.out ,我得到: ls: write error: Bad file descriptor

這是我的子進程的代碼(這是在fork()之后):

int _child(struct command *c){
    int ret;
    /* When given `ls > foo.out`, these next two lines output:
    ** c->infile is (null)
    ** c->outfile is foo.out
    */
    printf("c->infile is %s\n",c->infile);
    printf("c->outfile is %s\n",c->outfile);
    if(c->infile){
        int fd = open( c->infile, O_RDONLY);
        int _fd_dup = dup2(fd,0);
        close(0);
        if(_fd_dup != 0){
            fprintf(stderr, "Failed to redirect command input.\n");
            return 0;
        }
    }
    if(c->outfile){
        int fd = open( c->outfile, O_WRONLY | O_CREAT | O_TRUNC, 0600);
        int _fd_dup = dup2(fd,1);
        close(1);
        if(_fd_dup != 1){
            fprintf(stderr, "Failed to redirect command output.\n");
            return 0;
        }
    }

我沒有得到“無法重定向命令輸出。” 錯誤。 正如我所提到的,這是一項家庭作業,所以我不是在尋找任何人來解決這個問題,而是指出我正確的方向。

問題在於這段代碼:

    int _fd_dup = dup2(fd,1);
    close(1);

你應該關閉fd ,而不是1 在fd 0情況下你也有同樣的問題。

暫無
暫無

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

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