c - detecting end of stream
I am writing a c application and want to execute some external programs and parse the output similar to writing a script and using expect.
How do I set the timeout for executing a task? How do I know that there is no more data to read from a stream, ie. it is waiti开发者_如何学Cng for input?
Thanks,
Walter
You can use select() to check if there are bytes available to be read from the stream. If there are none, it's a good indication that the external program is not outputting things - it's either waiting for input or simply busy working. I don't think there's a generic way to tell the difference between the two states.
Assuming you are working on a POSIX compliant system:
You can timeout on the task's input stream by polling on it with a function like select
. (See this tutorial). the end of stream is detected using the feof
function.
How do I set the timeout for executing a task?
Use select()
and set a timeout. Invoke this before you call recv()
.
How do I know that there is no more data to read from a stream, ie. it is waiting for input?
This is trickier. You need to have some protocol so that the sending side can alert the receiving side that it is finished. The HTTP approach is just to close the socket on the sending side, which causes the receiving side's recv()
to return zero bytes.
An alternative is that the sending side send a special character or character sequence. Another approach, depending on your application, you may have an exact number of bytes to transmit; this is rare though.
精彩评论