Print time while waiting for input - c

I'm trying to create simple program that requests a user to input a number but in the upper section I display a clock that updates every second.
Here's what I know
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int a;
int main(void) {
int a =1;
while(a)
{
system("cls");
time_t rawtime;
struct tm* time_;
time(&rawtime);
time_ = localtime(&rawtime);
printf("%i:%i:%i %i %i %i\n", time_->tm_hour, time_->tm_min,
time_->tm_sec, time_->tm_mday, time_->tm_mon+1,
time_->tm_year+1900);
printf("Give the input :");
scanf("%d",&a);
}
return 0;
}
I took the printing time code from Program a simple clock in C
What my code does is print the time and then it waits for the input, but it doesn't update the clock until I give the input.
Is there any possible way to do what I want or what keyword do I needed to search the solution?
I'm sorry if my English broken, but if what I say isn't clear enough just run the code :).

There are only two ways to display something while waiting for input:
use non blocking IO and poll for user input while constantly updating the displayed time. That will be easy with a GUI library or through non portable system calls - sadly non longer standard portable C
use 2 threads, one for updating the display, the other for user input. It is almost portable since C11, except that the support for C threads is optional. And it will lead to a much more complex program
TL/DR: Even if it looks simple (and was indeed possible with basic language in the 80' on any personnal computer), non blocking terminal IO is far from simple in C language because of the assumption that the terminal is just a special case of IO.

Your problem is simple: you can't wait for an user input and do something else meanwhile, unless you use threads. May be what you could do is to wait for an input for a certain amount of time, print time and loop.
Otherwise, just know that using thread is not really complicated, but it will increase significantly the complexity of your program which purpose seemed to remain simple.

What you want is "non-blocking I/O".
How do you do non-blocking console I/O on Linux in C?
There is an answer in the above linked question that has a code snippet. The accepted answer also states that:
you pretty much don't do non-blocking I/O
and if you have to, you will
simplify this another way, by putting the console I/O into a thread or lightweight process.
The code snipped is hideously complicated and in my experience not guaranteed to work.

Related

Subtracting and getting seconds as input in C

I have the following code:
#include <stdio.h>
#include <time.h>
int main(){
clock_t timerS;
int i=1, targetTime=2;
scanf("%d", &targetTime);
while(i!=0){
timerS = clock();
while ((double)((clock() - timerS) / CLOCKS_PER_SEC) < targetTime){
//do something
}
//do another thing but delayed by the given time
if(targetTime>=0.5)
targetTime-=0.02;
else i=0;
}
return 0;
}
And what I want to do is having a loop which does something for (initially) an inputted amount of seconds and also doing another thing after targetTime-seconds have passed.
But after the first loop, to change the speed with which these operations are made(more specifically -0.02 seconds in this case).
An example would be getting multiple user inputs from user for 2 seconds, and displaying all the inputs made in these 2 seconds afterwards.
First problem is
If the initial given time is smaller than 1 second (for example 0.6), the other thing isn't delayed by 0.6 seconds, but is done immediately.
Second problem is
Actually similar to the first, if I subtract 0.02 seconds (in this case) from targetTime, it again does the other thing immediately and not in targetTime-0.02 seconds as I intend it to.
I'm new to this "clock" and "time" topic in C so I guess I'm doing something wrong regarding how these operations should be done. Also, please don't give an overly-complicated explanation/solution because of the above-mentioned reason.
Thanks!
Don't use the clock(2) system call, as it is obsolete and has been fully superseeded by machine independent replacements.
You can use, if your system supports it, clock_gettime(2), that will give you up to nanosecond precission (depending on the platform, but at least in linux on Intel architectures it is almost warranted) or, if you cannot use it, at least you'll have gettimeofday(2), which is derived from BSD systems, and provides you with a clock with microsecond resolution.
If you want to stop your program for some delay, you have also sleep(2) (second based) usleep(2) (microsecond based) or even nsleep(2) (nanosecond based)
Anyway, any of these calls has a tick that is not based on the system heartbeat, and the resolution is uniform and not system dependant.
I mistakenly initiated targetTime as int instead of double. Changing it to double solves the issue easily. Sorry!

What is the efficient way to continuously check until a condition is true

So I have this program that continuously check until the condition is true. My problem is whenever I run it, my computer slows down because of the loop. Can anyone please suggest the best and most efficient way to do this? Thank you for your response in advance.
To illustrate my problem, here is a code that represents it:
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <windows.h>
int main(void){
time_t now;
struct tm *local;
while(1){
time(&now);
local = localtime(&now);
if(local->tm_min > 55){
printf("Time:\t%d:%d:%d\n",local->tm_hour,local->tm_min,local->tm_sec);
getch();
exit(0);
}
}
return 0;
}
If polling is really what you want, or you have to use it, then you must give breath to the system by using sleep's.
So, how much to sleep in each iteration? It can be a fixed value (and if you sleep just 1 millisecond you will be stunned at how this is effective). A fixed value, say 20-30 milliseconds is good if you check for slow events like keystrokes by a real user. If, say, you are monitoring a serial port, perhaps you need lower values.
Then, depending on the application, you can also implement a variable sleep time. For example (this is a little stupid but it is just to explain): you wait for keystrokes, and sleep 30 milliseconds. Then you use your program in a pipe and discover that it is painly slow. A solution could be to set the value to sleep equal to 30 ms, but after having read a character, the value is lowered to 0 which causes the sleep to be not performed. Every time the condition fails the value is raised up to the maximum limit (20-30 milliseconds for a keyboard).
-- EDIT AFTER COMMENTS --
It has pointed out that keyboards and serial ports do not need polling, or they should not be polled. Generally speaking this is true, but it depends on the hardware and operating system (which in turn is a piece of software and, if the hardware does not support an interrupt for a given condition, even the OS would have to poll). About keyboards, for example, I thought at those little ones implemented as a matrix of buttons: some small CPUs have special facilities to generate an interrupt on any I/O change, but other don't: in that case polling is the only solution - and it is also ideal for implementing anti-bouncing (this kind of polling is not necessarily performed inside a loop).
For serial ports, it is almost true that nobody would implement one without an interrupt (to avoid polling). But even so, it is difficult to manage the incoming data in an event-driven fashion; often a flag is set, and some other part of the program, which polls that flag, will work out the message.
Event-driven programming seems easy at first, but as soon the program gets bigger the complication augments too.
There are other situations to consider, for example loops which read data from somewhere and process those data. If something else has to be done inside the loop, for example checking how much time is passed, but the reading is blocking, the reading must be implemented in a non-blocking way, and the whole loop must turn into a kind of polling for one or more conditions -unless one uses multi-threading.
Anyway, I agree that polling is evil and should only be used when necessary.
Efficiently? One way or the other you need to put your process to sleep until the condition WILL BE TRUE - then wake up and die (so to speak :-). Since your code includes windows.h I'll assume you're running on Windows and thus have the Sleep() function available.
#include <stdio.h>
#include <windows.h>
#include <time.h>
int main(void)
{
time_t now;
struct tm *local;
DWORD msecs;
time(&now);
local = localtime(&now);
/* (55 * 60000) = msecs in 55 minutes */
msecs = (55 * 60000) - ((local->tm_min * 60000) + (local->tm_sec * 1000));
if(msecs > 0)
Sleep(msecs)
return 0;
}

C: How to check if the computer is locked/sleep?

Is there any function in C to check if the computer is going to sleep,hibernate or locked and waking up from these state?
In msdn they provided for C#, C++ but not for C.
My OS is windows7
Like below is the code I'm using to check the time duration between starting the program and terminating it(shutting down the system will terminate the program so this way time duration can be measured).
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include<time.h>
clock_t start_time=0;
void bye (void)
{
FILE *read,*write;
write=fopen("F:\\count.txt","w");
clock_t end_time=clock();
fprintf(write,"Time: %d",(end_time-start_time)/CLOCKS_PER_SEC);
fclose(write);
}
int main (void)
{
start_time=clock();
atexit (bye);
//exit (EXIT_SUCCESS);
getch();
}
In the same way I want to check for locked/sleep/hibernate.
One possible way to wrap the c++ code(provided in the link) in c as mentioned by #ddriver
But is it not possible in C at all?
The WinAPI has generally at least the same possibilities as .NET framework. What your are asking for is the PowerManagement API.
You will have to register to receive PowerSettingNotificationEvents with the RegisterPowerSettingNotification function. Unfortunately, it is used differently for a GUI application where you give a handle to a window that will then receive a WM_POWERBROADCAST message each time the system is about to change state (one of the suspend modes or the hibernate mode), and for a non GUI (typically a service) that registers a HandlerEx callback with a dwControl parameter of SERVICE_CONTROL_POWEREVENT and a dwEventType of PBT_POWERSETTINGCHANGE.
The link you provide is about signals, emitted when power mode is changing. So, obviously, you can check when the system is about to go to sleep, or it just woke up.
As of checking if the system currently sleeps, that is simply not possible, as user code will simply not be running during deep sleep states. Maybe some platform specific, very low level BIOS API, but those are usually not public, and far from portable.

Why doesn't Linux prevent spawning infinite number of processes and crashing?

With the very simple code below, my system (Ubuntu Linux 14.04) simply crashes not even letting my mouse respond. I had to force quit with the power button. I thought Linux is a stable OS tolerable of handling such basic program errors. Did I miss something?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
void check(int isOkay){
if(!isOkay){
printf("error\n");
abort();
}
}
int main(void){
#define n 1000000
int array[n];
sem_t blocker;
int i;
while(1){
if(!fork()){
for(i = 0; i < n; ++i){
array[i] = rand();
}
check(sem_init(&blocker, 0, 0) == 0);
check(sem_wait(&blocker) == 0);
}
}
return 0;
}
Congratulations, you've discovered the fork bomb. There are shell one-liners that can wreak the same sort of havic with a lot less typing on your part.
It is in fact possible to limit the number of processes that a user can spawn using ulimit -- see the bottom of the linked wikipedia articles for details.
A desktop install of Ubuntu is not exactly a hardened server, though. It's designed for usability first and foremost. If you need a locked down system that can't crash, there are better options.
The command ulmit -u shows the maximum number of processes that you can start. However, do not start that many processes in the background: your machine would spend time switching between processes and wouldn't get around to getting actual work done.
The linux does its job of processing your request to create a process, it is for the user to implement his code based on this limit.
The main problem here is determining the best limit. A lot of software doesn't use fork() at all, so do you set the limit to something small like 5? Some software might create a new process whenever it receives a request from network, so do you set the limit to "max. number of network packets"? If you assume most software isn't buggy, then you'd be tempted to set the limit relatively high so that correct software works properly.
The other problem is one of scheduling priorities. In a well designed system things like the GUI would be "high priority" and if it wants CPU time it'd preempt normal/lower priority work immediately. If this was the case, a massive fork bomb running at normal/lower priority would have no effect on the system's ability to respond to the user, and the user would be able to kill the fork bomb without much problem.
Sadly, for a variety of reasons, the scheduler in Linux doesn't work like that. It does support priorities, but to use them you have to be a "real time" process and have to be running as root (which is a massive security disaster). Without sane priorities, Linux assumes that every forked process is as important as everything else, and the CPU/s end up busy doing the forking and there's no CPU time left to respond to the user.

Waiting maximum of X time for input, then proceeding with the program?

Hello I'm creating a game in C.
I want there to be a frame printed every 0.1 seconds. During that time, the user may or may not input using getch().
How do I write such a program? Heres what I can offer you guys to work with.
do{
usleep(100000); // simple 100 mili second delay
if (getch()==32) (ASCII for a space) // may or may not be inputed in 0.1 second timeframe.
playerJumps;
// even if user inputs early, I still want game printed exactly every 0.1 sec not sooner/later.
printGame;
}while(notDead);
I really hope I kept code nice and clear
I've done this before, you are going to have to talk about what platform you are on. All of the C library input functions block to wait for input. One way to do it is with threads -- you have one thread block on the user input, and the other does the game, and it gets notified by the input thread when there is input. The other way is to use a function like poll() on linux, which I believe is what I used, they basically allow you to specify a wait period, or to just try to see if there is input and return immediately if there isn't. Though I think select() should also work, and I think that should be relatively cross platform.

Resources