Why doesn't this small C program work as expected? - c

I've got a small C program that makes use of difftime. its really strange, it doesn't print out the line after 10 seconds.
If however I uncomment out the sleep line then it works.
Any ideas why this is happening?
/* difftime example */
#include <stdio.h> /* printf */
#include <time.h> /* time_t, struct tm, difftime, time, mktime */
int main ()
{
time_t start, stop;
start = time(NULL);
for(; /* some condition that takes forever to meet */;) {
// do stuff that apparently takes forever.
stop = time(NULL);
double diff = difftime(stop, start);
//sleep (1);
if (diff >= 10) {
printf("10 seconds passed...");
start = time(NULL);
}
}
}
BTW: Code compiles fine and I'm running it on the Raspberry Pi.
3.6.11+ #474 PREEMPT Thu Jun 13 17:14:42 BST 2013 armv6l GNU/Linux

Console IO might be line buffered. Try flushing
printf("10 seconds passed...");
fflush(stdout)
or adding a newline \n
printf("10 seconds passed...\n");
I can't reproduce any change in behaviour when the call to sleep is uncommented.

printf("10 seconds passed...\n");

For sleep(), you need to include unistd.h, as well as adding a newline as others have pointed out.
#include <stdio.h> /* printf */
#include <time.h> /* time_t, struct tm, difftime, time, mktime */
#include <unistd.h> /* sleep() */
If your code compiled without warnings and without including unistd.h, you need to crank your warnings up.

Related

What function clears the screen on a mac terminal?

I'm new to C and I do not own a mac, but I'm working on a personal project for someone who does and part of the project's requirements is that it clears the screen. The reason I need to clear the screen is that it's part of a loop that clears the screen and then prints something again (I'm trying to make a "ticking counter" of sorts.)
I know that system("cls") works well on my terminal (obviously any system function isn't ideal though), however, I know that she's on a Mac OS, and that the system() function is notoriously nonportable and I need this to work on a mac. I've scoured the internet trying to see what system functions clear the screen on a mac, and the most recent source I could find was from 2006. Considering how often the mac gets updated, I'm not surprised that
I don't really need a solution that's elegant or secure, just an idea for something that works. My compiler is MinGW with GCC for libraries.
Here's a sample of the relevant code:
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
int main()
{
time_t seconds; //variable declarations
float days;
float rate;
int i;
i = 3;
char str[50];
while (i > 2);
{
time(&seconds);
days = (seconds - ((float)1584673594)) / (float)86400;
rate = pow(1.05, days);
rate = rate * 100;
printf("\nCurrent Snuggle-Debt Balance: %f snuggles\n", rate);
printf("Days passed: %f \n", days);
sleep(.5);
system("cls");
If you're writing a C program that uses standard input and output, and you need to do things like move the cursor around or clear part or all of the screen, the curses library is what you want. Curses is widely available and does what you want and much more. To clear the screen, just call the clear() function. And that's just the beginning of what you can do.

Modifying the time function in C

For a computer security assignment, I have to modify the time function in order to return a specific date. I need the time function to return a date between Jan 1st, 2016 and June 15th, 2018. I then use these commands to overload and hook into the time function:
gcc -Wall -fPIC -shared -o newtime.so newtime.c -ldl
export LD_PRELOAD=$PWD/newtime.so
Here is my modified version of the time function:
#define _GNU_SOURCE
#include <dlfcn.h>
#include <time.h>
time_t time (time_t *t)
{
long int seconds = 1485907200;
time_t modifiedTime = (time_t) seconds;
return modifiedTime;
}
Whenever I run this implementation, it says that the date being returned is December 31, 1969 19:00:00. Am I just formatting the time since the Linux Epoch incorrectly or am I making a more serious mistake? I have tried using a regular int instead of a long int, and still experience the same issues. Some insight into my mistake would be very helpful.
You're not implementing the entire functionality of time(). The code your interposing on may use functionality that you have not implemented.
Per the C standard:
7.27.2.4 The time function (note the bolded part):
Synopsis
#include <time.h>
time_t time(time_t *timer);
Description
The time function determines the current calendar time. The encoding
of the value is unspecified.
Returns
The time function returns the implementation's best approximation to
the current calendar time. The value (time_t)(-1) is returned if the
calendar time is not available. If timer is not a null pointer, the
return value is also assigned to the object it points to.
A full implementation, based on your code:
time_t time (time_t *t)
{
long int seconds = 1485907200;
time_t modifiedTime = (time_t) seconds;
if ( t )
{
*t = modifiedTime;
}
return modifiedTime;
}
In fact, there is no problem in the code that you presented. I tested it with the following basic program:
#include <stdio.h>
#include <time.h>
int main(void)
{
printf("%ld\n", (long) time(NULL));
}
So I just run LD_PRELOAD=./newtime.so ./test and I get the expected result.
However, the date command doesn't make call to the time function. It calls instead int clock_gettime(clockid_t clk_id, struct timespec *tp). So you should better re-implement them both if you would like to cover this case.
May be a simple implementation like the following one (It works fine with date):
int clock_gettime(clockid_t clk_id, struct timespec *tp)
{
if(tp) {
tp->tv_sec = 1485907200;
tp->tv_nsec = 0;
}
return 0;
}
If you get a date different from your expectation, it could be related to your time zone.

How to pause for a non-integer amount of time in C?

I'm writing a simple program, and it gives me an error when I pass a non-integer value to the sleep() function. Is there another function, or a different way to use sleep(), that will allow me to pause the program temporarily for less than a second (or, say, 2.5)?
mario.c:34:13: error: implicit declaration of function 'usleep' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
usleep(30000);
^
usleep will pause for a particular number of microseconds. For example:
usleep(500000);
will pause for half a second.
On some systems, and depending on compiler configuration etc, you may need to define _GNU_SOURCE before including unistd.h (ideally, at the start of the source file), with:
#define _GNU_SOURCE
POSIX.1-2001 standard defines function nanosleep(), which is perfect for this. Unlike sleep() and usleep(), nanosleep() does not interfere with signals.
Current Linux C libraries tend to implement usleep() as a wrapper around nanosleep(), however. You can see this if you strace a test program (say, run strace /bin/sleep 1).
However, as nanosleep() is part of POSIX.1-2001 standard, it is definitely recommended.
For example:
#define _POSIX_C_SOURCE 200112L
#include <time.h>
#include <errno.h>
/* Sleep; returns un-slept (leftover) time.
*/
double dsleep(const double seconds)
{
const long sec = (long)seconds;
const long nsec = (long)((seconds - (double)sec) * 1e9);
struct timespec req, rem;
if (sec < 0L)
return 0.0;
if (sec == 0L && nsec <= 0L)
return 0.0;
req.tv_sec = sec;
if (nsec <= 0L)
req.tv_nsec = 0L;
else
if (nsec <= 999999999L)
req.tv_nsec = nsec;
else
req.tv_nsec = 999999999L;
rem.tv_sec = 0;
rem.tv_nsec = 0;
if (nanosleep(&req, &rem) == -1) {
if (errno == EINTR)
return (double)rem.tv_sec + (double)rem.tv_nsec / 1000000000.0;
else
return seconds;
} else
return 0.0;
}
Most of the logic above is to make sure (regardless of floating-point rounding mode et cetera) that the nanoseconds field is always within [0, 999999999], inclusive, and to make it safe to call it with negative values (in which case it'll just return zero).
If you want to specify the duration in integer milliseconds, you could use
#define _POSIX_C_SOURCE 200112L
#include <time.h>
#include <errno.h>
/* Sleep; returns un-slept (leftover) time.
*/
long msleep(const long ms)
{
struct timespec req, rem;
if (ms <= 0L)
return 0L;
req.tv_sec = ms / 1000L;
req.tv_nsec = (ms % 1000L) * 1000000L;
rem.tv_sec = 0;
rem.tv_nsec = 0;
if (nanosleep(&req, &rem) == -1) {
if (errno == EINTR)
return (long)rem.tv_sec * 1000L + rem.tv_nsec / 1000000L;
else
return ms;
} else
return 0L;
}
It is not necessary to zero out rem, above, but written this way, these two functions are extremely robust, even against an occasional system hiccup or library bug.
The apparent problem with the original suggestion to use usleep was overlooking _GNU_SOURCE, a given for Linux with almost any POSIX-extension.
This compiles without warning for me, using c99 with the strict warning flags:
#include <unistd.h>
#include <time.h>
int main(void)
{
usleep(1);
nanosleep(0,0);
return 0;
}
and (extracted from other scripts)
ACTUAL_GCC=c99 gcc-stricter -D_GNU_SOURCE -c foo.c
#!/bin/sh
OPTS="-O -Wall -Wmissing-prototypes -Wstrict-prototypes -Wshadow -Wconversion
-W
-Wbad-function-cast
-Wcast-align
-Wcast-qual
-Wmissing-declarations
-Wnested-externs
-Wpointer-arith
-Wwrite-strings
-ansi
-pedantic
"
${ACTUAL_GCC:-gcc} $OPTS "$#"
The usleep and nanosleep functions are extensions, as noted. More commonly, select or poll are used. Those functions are used to wait for a specified interval of time for activity on one or more open files. As a special case, select does not even have to wait for a file, but simply use the time interval. Like nanosleep, select uses a structure for the time interval to allow double-precision values -- but its range of values starts with microseconds while nanosleep starts with nanoseconds.
These functions are all part of the Linux C library.
ncurses (like any X/Open curses) provides a function napms which waits for milliseconds. Internally, ncurses uses (since 1998) nanosleep or usleep depending on their availability (they are extensions after all), or an internal function that uses select or poll, also depending on availability.
Use this macro to pause for non-integer seconds:
#include "unistd.h"
#define mysleep(s) usleep(s*1000000)
sleep()'s int value is for a pause time in milliseconds, not seconds. So, to pause for one second, you'd pass it 1000. For 2.5 seconds, you'd pass it 2500. For a half second, you'd pass 500.
This will let you specify a delay as a float in seconds.
The function executes until the difference between start and stop is greater than the requested delay.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void floatdelay ( float delay);
int main()
{
float pause = 1.2;
floatdelay ( pause);
return 0;
}
void floatdelay ( float delay)
{
clock_t start;
clock_t stop;
start = clock();
stop = clock();
while ( ( (float)( stop - start)/ CLOCKS_PER_SEC) < delay) {
stop = clock();
}
}

Minix current time

How to write current time in printf on Minix 3.2.1?
I try to use gmtime like below but it gives error on time(&nowtime).
#include <sys/time.h>
#include <time.h>
struct tm *now;
time_t nowtime;
time(&nowtime);
now=gmtime(&nowtime);
printf("TIME is NOW %s",now);
Moreover, I try to recall that in kernel (/usr/src/kernel/main.c) because I need that time on the booting of minix to say when the kernel process is finished and switch to user.
I take some errors on above code like when rebuild the kernel like below;
Not that familiar with minix, but it is similar to Unix & Linux, so maybe something from that platform may be present on minix... so A couple of approaches
Run a man on ctime
the man page on Linux's time() command contains this example code (which you may have to modify for minix, but it shows how to use asctime() localtime() and time() ):
#include <stdio.h>
#include <time.h>
int main(void)
{
time_t result;
result = time(NULL);
printf("%s%ju secs since the Epoch\n",
asctime(localtime(&result)),
(uintmax_t)result);
return(0);
}

c daemon() for unix doesnt work with sleep()

I have very simple code that should run on background and at 1 am shut down the computer:
#include <ctime>
#include <cstdlib>
#include <unistd.h>
int main() {
time_t t;struct tm * now;
daemon(0,0);
while(1){
t = time(0);
now = localtime( & t );
if(now->tm_hour==1){
system("shutdown -P");
break;
}
sleep(10);
}
return 0;
}
The code works without sleep(10) but uses whole free memory so I need sleep function there to stop loop and recheck time each ten seconds, but with sleep function program stops immediately after I run it.
If you are writing C code, don't use C++ headers (ctime, cstdlib). Replace those #includes with #include <stdlib.h> and #include <time.h>. If the behavior of this code is really as you describe (which I would find surprising), then this is probably the source of the error.
Of course it immediately exits. Thats the whole point of using daemon. Check with ps and you will see that your proram is still running as a seperate process now.
Check the man page for a desription how daemon works.

Resources