ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
I have a small program that reads stdin from a pipe using fgets. Now fgets blocks for the first line but after that it will not block.
THE CODE, my_echo.c -
int main(int argc, char **argv)
{ char buf [2000] ;
char* pc ;
printf("hello\n") ;
while (1)
{ buf[0] = (char) 0 ;
pc = fgets(buf, sizeof(buf), stdin);
if (pc != NULL)
printf("%s\n",buf);
}
return 0;
}
HOW ITS CALLED
* In terminal window 1: ./my_echo < my_fifo
* In terminal window 2: echo "1234" > my_fifo
* In terminal window 1: prints hello then 1234.
* Checking with ksysguard or top shows that my_echo
is consuming 40% of CPU time.
Adding a few printf's shows that the gets is not
blocking and returns a null pointer.
* In terminal window 2: echo "qwerty" > my_fifo
* In terminal window 1 qwerty prints.
MY PROBLEM : I want a read function that does in fact block so my program does not tie up CPU time, read does not block. Any ideas anyone?
Ah, well, on my Fedora system, a man 7 pipe gives a nice overview of pipe operations. That overview suggests that, if you create your pipe using a mkfifo call, then the read will be blocked when the pipe is empty.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.