简体   繁体   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. 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. What I have written:我写的是:

foo.c 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;
}

bar.c酒吧.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;
}

When I use./foo.exe /etc/passwd for example, it just waits and does nothing, the same for./bar.exe.例如,当我使用./foo.exe /etc/passwd 时,它只是等待并且什么也不做,对于./bar.exe 也是如此。 Any suggestions and comments would be helpful.任何建议和意见都会有所帮助。 Also, do I have to use mkfifo(name, 0666) in bar.c again or it is not necessary.另外,我是否必须再次在 bar.c 中使用 mkfifo(name, 0666) 或者没有必要。

Converting my comment into an answer.将我的评论转换为答案。

The open of the FIFO for writing won't complete until there is a reader;直到有读卡器,写入的FIFO的打开才会完成; the open for reading won't complete until there is a writer.在有作家之前,开放阅读不会完成。

How are you running the programs?你是如何运行程序的? If you start foo in one terminal and bar in another, it should work.如果您在一个终端启动foo并在另一个终端启动bar ,它应该可以工作。 If you try to run them in the same terminal, you'll need to run one in the background before running the other.如果您尝试在同一个终端中运行它们,则需要先在后台运行一个,然后再运行另一个。 Running them sequentially in a single terminal will not work – the first one run won't finish, so the second won't start.在单个终端中按顺序运行它们是行不通的——第一个运行不会完成,所以第二个不会启动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM