Reputation:
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
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
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. 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.
Upvotes: 0
Views: 45
Reputation: 753930
Converting my comment into an answer.
The open of the FIFO for writing won't complete until there is a reader; 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. 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.
Upvotes: 1