簡體   English   中英

命名為 pipe 和 execlp

[英]Named pipe and execlp

I am trying to create a named pipe and my first program foo.c has to execute cat command with the given argument to the foo.c program, then the second program has to receive the output from foo.c and sort it. 我寫的是:

foo.c

int main(int argc, char*argv[]){
        char* name="fifo";
        if(mkfifo(name, 0666)==-1){
                printf("error in mkfifo");
                return -1;
        }

        int fd=open(name, O_WRONLY);
        if(fd==-1){
                printf("error in opening");
                return -1;
        }

        int f1=fork();
        if(f1==-1){
                printf("error in fork");
                return -1;
        }

        if(f1==0){
                close(1);
                dup(fd);
                execlp("cat", "cat", argv[1], NULL);
        }

        close(fd);

        return 0;
}

酒吧.c

int main(int argc, char*argv[]){
        char*name="fifo";

        int fd=open(name, O_RDONLY);
        if(fd==-1){
                printf("error in opening");
                return -1;
        }

        int f1=fork();
        if(f1==-1){
                printf("error in fork");
                return -1;
        }

        if(f1==0){
                dup2(fd, 0);
                execlp("sort", "sort", NULL);
                close(fd);
        }

        return 0;
}

例如,當我使用./foo.exe /etc/passwd 時,它只是等待並且什么也不做,對於./bar.exe 也是如此。 任何建議和意見都會有所幫助。 另外,我是否必須再次在 bar.c 中使用 mkfifo(name, 0666) 或者沒有必要。

將我的評論轉換為答案。

直到有讀卡器,寫入的FIFO的打開才會完成; 在有作家之前,開放閱讀不會完成。

你是如何運行程序的? 如果您在一個終端啟動foo並在另一個終端啟動bar ,它應該可以工作。 如果您嘗試在同一個終端中運行它們,則需要先在后台運行一個,然后再運行另一個。 在單個終端中按順序運行它們是行不通的——第一個運行不會完成,所以第二個不會啟動。

暫無
暫無

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

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