how can i make read (or other equivalent function) be in blocking mode for a specific time from the time that function reach execution
or in other words, to wait for an amount of time in which is trying to read
Maybe alarm could be a viable option for simple cases
A probably better solution would involve blocking on a select (or similar) call with a specified timeout and monitor the file descriptor for reading
Your question is fairly vague, so I can only assume what you mean. I guess you are wanting to attempt to 'read' until a certain deadline or timeout has been reached. In which case, just put the call to the read function inside a while loop which checks the current time against some pre-determined deadline and exits the loop when it has been reached....
Related
I wrote a CPU intensive program in C to run on Windows. In the main loop I check for a keyboard press to allow you to interrupt execution in order to pause the program. The idea is to release the thread to other processes if the program is slowing down the computer too much. After a keyboard press I wait for more keyboard input using fgets(), which allows you to restart the program later. This does reduce the CPU usage shown in task manager quite well. But I was wondering if there is perhaps a more explicit way to tell the operating system that this process doesn't need any attention for a while in order to reduce the overhead while idle to the absolute minimum.
My understanding is that the operating system periodically lets a process run and then stops running it after a certain amount of time. It then checks the rest of the processes in the same way until it comes back to this one again. If it has enough to do the process will run for the maximum allowed time. Otherwise, it will stop early and return control to the operating system. So a function like fgets must immediately return control if there is no keyboard input, which is why the process runs at near 0% CPU. So I guess another way of asking my question is how do I deliberately return control to the operating system in my own code.
my question is how do I deliberately return control to the operating system in my own code
You can use either Sleep(0) or SwitchToThread(). Both pass control back to the OS and might cause the calling thread to give up the remaining time slice but the devil is in the detail.
Sleep(0)
If no other thread with a matching priority is ready to run, the call returns immediately. Otherwise, the thread gives up its remaining time slice.
You can work around the priority issue by using SwitchToThread or Sleep(1). The disadvantage of the latter is that the thread gives up its time slice unconditionally, whether or not other threads are ready to run.
SwitchToThread()
If no other thread, irrespective if its priority, is ready to run on the thread's current processor, the call returns immediately. Otherwise, the thread gives up its remaining time slice for at most one time slice.
Alternatively, you could change the priority of the process (SetPriorityClass() with PROCESS_MODE_BACKGROUND_BEGIN) or thread (SetThreadPriority() with THREAD_MODE_BACKGROUND_BEGIN) so that the OS can take care of prioritizing more important processes/threads for you. In your scenario, doing so would be a better fit. The scheduler will respond to sudden CPU demand without any additional work on your end.
You can do it in pretty much two ways. Either read the input using a blocking function, like fgets, or read the input using a non-blocking function. In the second situation you would need to incorporate a timeout of some sort. Some functions do this for you, like select. Otherwise you need to regularly sleep your process or thread.
Effectively the system is using interrupts to determine which processes care about a specific event.
I have a Win32 console program written in C, that needs to terminate when a certain length of time has elapsed, even if it's still busy. At the moment I'm doing this:
static VOID CALLBACK timeout(PVOID a, BOOLEAN b) { ExitProcess(0); }
...
HANDLE timer = 0;
CreateTimerQueueTimer(&timer, 0, timeout, 0, (DWORD)(time_limit * 1000),
0, 0);
This works fine in the case where the program is computationally busy when the time limit is reached, e.g. it easily passes a test case where I put an infinite loop in main. However, there is a situation where it doesn't work, and the program just stays hung indefinitely. The situation has to do with being called by a parent process, I don't know exactly what's going on, have asked a separate question about that. My question here is:
Is there a way to tell Windows to really kill the current process after a certain number of seconds, no matter what?
Update: experimented just now, WT_EXECUTEINTIMERTHREAD seems to solve the problem. That leaves a few questions:
Why does that flag matter?
If I'm not using any other time operations in the program, is it safe to ignore the warning "This flag should be used only for short tasks or it could affect other timer operations."?
If more than one choice of flag will solve the problem, which flag is it best to use?
You can use SleepEx
Suspends the current thread until the specified condition is met. Execution resumes when one of the following occurs:
AN I/O completion callback function is called,
AN asynchronous procedure call (APC) is queued to the thread OR
The time-out interval elapses.
The 3rd, or 1st option is your best bet. The condition for the first function should be your desired situation, whatever the case is in your program. Or a pre-configured amount of time.
After SleepEx follow-up by a call to ZwTerminateProcess from NTDLL.DLL. This will ensure that the process is terminated as calling ExitProcess performs prior checks before calling ZwTerminateProcess/Thread. Here you can call it yourself and ensure termination! You can fill the HANDLE parameter for ZwTerminateProcess by passing GetCurrentProcess() to the argument. Alternatively, you obtain a HANDLE to a remote process by scanning the process list via ZwQuerySystemInformation->ZwOpenProcess, or Creating a snapshot (CreateToolhelp32Snapshot ... off the top of my head) followed by Process32First->Next->OpenProcess - You can then use ZwTerminateProcess to terminate the remote process given you have the SE_DEBUG_PRIVILEGE, and the current process is executing from the same integrity level as the other process!
Hello everyone i have a question about timeouts in c so i ask you guys.
So i'm making a server application in C that uses POSIX threads to accept multiple simpultenious connections but implementing timeouts was harder than i expected as i read the message (HTTP requests) in parts first the start line than the headers etc, etc, and i initialy used select() to detect if the socket was ready for reading but that way if the client sends the start line only than the server will continue waiting for the headers and body without ever timing out so what i did is i put all the code that reads the message in one function and i wan't to implement a timeout for the entire function, say if the function doesnt return in x seconds than a timeout function is called and the thread is exited...
[Things that i have tried]
putting multiple select calls (one for every socket read) but that ended up in a mess of having to calculate remaining time for each operation.
i didn't actually try to use an alarm signal as i've heard that signals effect the entire process and not a specific thread that would cause one time out to timeout every parallel connection..
thanx in advance.. B)
There is no proper way to terminate a thread function other than letting it finish.
Every attempt to finish a thread from the outside could lead to resource (mostly but not only memory) leaks, state variables in nondeterministic state, and so. Please don't do it. Never. The normal way of terminating a thread function from the outside is to make it listen to some means of inter thread communication (which can be a sync object, a volatile variable or even a message loop), and exit the function core when it is necessary. Normally you would realize it by having a single test in the cycle condition of the thread if it is looping or testing before every long-running operation inside your thread.
Now if you store the timestamp of the function start and test at every cycle condition/long-running test if currenttimestamp > timestamp + timeout, you can exit from inside your thread and voilá; your problem is solved.
I'm trying to understand how asynchronous file operations being emulated using threads. I've found next-to-nothing materials to read about the subject.
Is it possible that:
a process uses a thread to open a regular file (HDD).
the parent gets the file descriptor from the thread, now it may close the thread.
the parent uses the file descriptor with a new thread, reading X bytes from the file.
the parent gets the file descriptor with the seek-position of the current file state.
the parent may repeat these operations, without the need to open, or seek, every time it wishes to "continue" reading a new chunk of the file?
This is just a wild guess of mine, would appreciate if anybody mind to shed more light to clarify how it's being emulated efficiently.
UPDATE:
By efficient I actually mean that I don't want the thread to "wait" since the moment the file been opened. Think of a HTTP non-blocking daemon which serves a client with a huge file, you want to use the thread to read chunks of the file without blocking the daemon - but you don't want to keep the thread busy while "waiting" for the actual transfer to take place, you want to use the thread for other blocking operations of other clients.
To understand asynchronous I/O better, it may be helpful to think in terms of overlapping operation. That is, the number of pending operations (operations that have been started but not yet completed) can simutaneously go above one.
A diagram that explains asynchronous I/O might look like this: http://msdn.microsoft.com/en-us/library/aa365683(VS.85).aspx
If you are using the asynchronous I/O capabilities provided by the underlying Operating System, then it is possible to asynchronously read from multiple files without spawning a equal number of threads.
If your underlying Operating System does not provide asynchronous I/O, or if you decide not to use it, in other words, you wish to emulate asynchronous operation by only using blocking I/O (the regular Read/Write provided by the Operating System) then it is necessary to spawn as many threads as the number of simutaneous I/O operations. This is because when a thread is making a function call to blocking I/O, the thread cannot continue its execution until the operation finishes. In order to start another blocking I/O operation, that operation has to be issued from another thread that is not already occupied.
When you open/create a file fire up a thread. Now store that thread id/ptr as your file handle.
Basically the thread will do nothing except sit in a loop waiting for an "event". A semaphore would be good here. When you want to do a read then you add the read command to a queue (remember to critical section the stack add), return a unique id, and then you increment the semaphore. If the thread is asleep it will now wake up and grab the first message off the queue and process it. When it has completed you remove the command from the queue.
To poll if a file read has completed you can, simply, check to see if its in the command queue. If its not there then the command has completed.
Furthermore if you want to allow synchronous reads as well then you can wait after sending the message through for an "event" to get triggered by the completion. You then check to see if the unique id is the queue and if it isn't you return control. If it still is then you go back to a wait state until the relevant unique id has been processed.
there is any way to run an infinite cycle that stops only on user input from keyboard
without asking every cycle to continue? in a C program
(I'm developing a C chat that read the entries with a for(;;) loop and I need to stop it only when the user want to type and send a message) hi all!
You didn't specify the OS so I will assume some POSIX compliant OS.
You can use select. This can be used to block on a set of file descriptors (in your case, stdin) with a finite timeout or indefinite blocking.
My guess is, since this is a chat program, you would also want to do this on some other file descriptor, like your chat tcp socket. So you can test for input on both with one call.
In case of windows console, you should be able to use GetStdHandle and WaitForSingleObject/WaitForMultipleObjects if select does not work for you.
There are a number of ways of doing this in Windows. Assuming you're using VC++, the easiest way is probably to use _kbhit(). If you want to use the Win32 API directly instead, you could call GetNumberOfConsoleInputEvents() and see whether the return is non-zero.
You could also do an overlapped read, and each time through the loop call WaitForSingleObject with a timeout value of 0. The zero wait means it'll return immediately whether there's input or not. The return value will tell you whether you have any data: WAIT_TIMEOUT means no data has been read yet, and WAIT_OBJECT0 means you have some data waiting to be processed.