Reputation: 601
i'm writing to a pipe until user enters the string "end". if the user enters the string "end", i suppose to go further. here I've to close the pipe and print the message "After Written to Pipe". But its not printing the line "After Written to Pipe" even i entered "end" string. How can i close the pipe and go further even-though there is no process to read the pipe?..
Hi here is my code.,
int main() {
int fd;
char *b, *c;
printf("Enter Str : ");
b = malloc(50);
gets(b);
while(strcmp(b,"end")!=0){
if(access("MSG",F_OK) != -1) // check pipe is already available.
{
fd = open("MSG", O_WRONLY);
write(fd, b, strlen(b) );
}
else
{
if( mkfifo("MSG", 0666) != -1) // create pipe if not available.
{
fd = open("MSG", O_WRONLY);
write(fd, b, strlen(b) );
}
}
printf("Enter Str : ");
gets(b);
}
close(fd);
printf("After Written to Pipe");
}
Upvotes: 3
Views: 6942
Reputation:
Named pipes are not the right tool here, since bash
offers no way to use them in a non-blocking mode.
You could write a tool in a programming language that acts like cat
, but doesn’t block. But none of the results I found made me happy enough to recommend them to you.
Otherwise it’s either sockets (using netcat
and localhost
), which unfortunately are insecure since every other user on your computer could access them too…
Or some kind of normal file that acts as a buffer. But there you’d have the problem on how to delete the lines you already read so it doesn’t flood, and race conditions, and all those nightmares.
I’m sorry, but there really isn’t a good solution here. To solve this the proper way, would require patching bash and cat to add an option to allow non-blocking behavior.
Upvotes: 1
Reputation: 409146
From the mkfifo(3)
manual page:
However, it has to be open at both ends simultaneously before you can proceed to do any input or output operations on it. Opening a FIFO for reading normally blocks until some other process opens the same FIFO for writing, and vice versa.
The above paragraph means that write
will block until there is someone reading from the FIFO, which is what you see in your program.
Upvotes: 1