Unable to time command execution within C (popen)? - c

I've been trying to time how long it takes for an invocation of popen to complete. popen initializes a process which then creates a pipe, forks, and invokes the shell. In my particular case, I'm using the call to read another programs stdout output.
The problem: I'm expecting the call I make to return the correct length of time it took the program to execute (around 15 seconds for a test program). What I get is that the program took no time at all to finish (0.000223s). Despite all the various functions I have tried, I seem unable to time the call correctly.
Here is a reproducible example of my problem. It is composed of the timing program and a child program that the timing program runs (the child takes about 15s to run on my system):
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
#endif
#define MAXBUF 10
static void gettime (struct timespec *t) {
#ifdef __MACH__
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), REALTIME_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
t->tv_sec = mts.tv_sec;
t->tv_nsec = mts.tv_nsec;
#else
clock_gettime(CLOCK_REALTIME, t);
#endif
}
int main (void) {
FILE *fp;
struct timespec tic, toc;
char *executableName = "./a.out";
char answer[MAXBUF];
gettime(&tic);
if ((fp = popen(executableName, "r")) == NULL) {
fprintf(stderr, "The file couldn't be opened.\n");
return 1;
}
gettime(&toc);
fgets(answer, MAXBUF, fp);
double elapsed = (double)(toc.tv_nsec - tic.tv_nsec) / 1E9;
fprintf(stdout, "The program says %s, and took %fs to run!\n", answer, elapsed);
pclose(fp);
return 0;
}
Here is the child program:
#include <stdio.h>
#include <stdlib.h>
int timeWastingFunction (long long n) {
if ((n % 2) == 0) {
return 1;
}
for (int i = 1; i < (n / 2); i += 2) {
if ((n % i) == 0) {
return 1;
}
}
return 0;
}
int main (void) {
int start = 687217000;
while (start--) {
timeWastingFunction(start);
}
fprintf(stdout, "Hello!");
return 0;
}
This might look a bit overdone, but I had previously tried using clock_t, (a CPU based timing facility) to do the timing, and gotten the same answers from it. I therefore tried this solution which you see above. I picked: CLOCK_REALTIME as it seemed appropriate for the job. I unfortunately don't have the option to specify if this clock is on a per-process or per-thread level though (I'd want it to be process independent).
Note: I haven't tried using gettimeofday yet, but I don't want to since its apparently inappropriate for timing this way, dependent on the date of the system using it, and being phased out in favor of clock_gettime.
Edit: Just to be clear, what happens when I run this is that the program calling popen will actually stall for the 15 seconds the other program takes to run, before printing the 'wrong' time. It doesn't immediately print the time implying it didn't wait for the call to complete.

popen() only fork and open a pipe. Your test only show the time that take popen() to create the child and the pipe.
A simple way to solve your problem is to get the time after your pclose(), note that will be not perfect because when you read the data return by your child, it could finish before your call to pclose()
Plus your solution to get the result is broken, you only make the difference between nanosecond, I found a solution on git:
void timespec_diff(struct timespec *start, struct timespec *stop,
struct timespec *result)
{
if ((stop->tv_nsec - start->tv_nsec) < 0) {
result->tv_sec = stop->tv_sec - start->tv_sec - 1;
result->tv_nsec = stop->tv_nsec - start->tv_nsec + 1000000000;
} else {
result->tv_sec = stop->tv_sec - start->tv_sec;
result->tv_nsec = stop->tv_nsec - start->tv_nsec;
}
return;
}
The last thing is that CLOCK_REALTIME should be used if you want the date. Here you just want a duration. So you should use CLOCK_MONOTONIC if it's available on your system because CLOCK_REALTIME can rollback. (REALTIME_CLOCK of host_get_clock_service() seam monotonic too).
CLOCK_MONOTONIC: Clock that cannot be set and represents monotonic time since some unspecified starting point.
REALTIME_CLOCK: A moderate resolution clock service that (typically) tracks time since the system last boot.
So the working code could look like that:
int main (void) {
FILE *fp;
struct timespec tic, toc;
char *executableName = "./a.out";
char answer[MAXBUF];
gettime(&tic);
if ((fp = popen(executableName, "r")) == NULL) {
fprintf(stderr, "The file couldn't be opened.\n");
return 1;
}
fgets(answer, MAXBUF, fp);
pclose(fp);
gettime(&toc);
struct timespec result;
timespec_diff(&tic, &toc, &result);
fprintf(stdout, "The program says %s, and took %lld.%.9lds\n", answer, (long long)result.tv_sec, result.tv_nsec);
return 0;
}
Credit:
How to subtract two struct timespec?
How to print struct timespec?

Related

sleep() function does not work and print is executed instantaneously

static void timeDelay(int no_of_seconds)
{
#ifdef _WIN32
Sleep(1000 * no_of_seconds);
#else
sleep(no_of_seconds);
#endif
}
void somefunction(){
printf("\t\t Load ... \n\t\t");
fflush(stdout);
for (int i = 1; i <= 60; i++)
{
fflush(stdout);
timeDelay(1);
if (i == 31)
printf("\n\t\t");
printf("*****");
}
}
I have included the header files too:
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
The stars are printed instantaneously.
I added fflush(stdout) after seeing the answers here. I also commented out the if (i==31) {} portion to check if that's causing the problem but it isn't. So what is wrong with my code?
According to the sleep() manpage...
NOTES
On Linux, sleep() is implemented via nanosleep(2). See the nanosleep(2) man page for a discussion of the
clock used.
So I have rewritten your program to use nanosleep. As you are working with WSL, I've dropped any reference to Win32, only Linux. Well, the thing is that this program exits nanosleep() prematurely, with an "Invalid argument" error. I cannot see why is that.
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <errno.h>
void timeDelay (time_t no_of_seconds)
{
struct timespec req, rem;
int res;
req.tv_sec = no_of_seconds;
req.tv_nsec = 0;
do
{
rem.tv_sec = 0;
rem.tv_nsec = 0;
res = nanosleep (&req, &rem);
req = rem;
}
while (res == EINTR);
if (res)
perror("nanosleep");
}
void somefunction()
{
printf("\t\t Load ... \n\t\t");
fflush(stdout);
for (int i = 1; i <= 60; i++)
{
fflush(stdout);
timeDelay(1);
putchar('*');
}
}
int main()
{
somefunction();
return 0;
}
I've also tried with NULL instead of rem, and reissuing nanosleep() with the original time instead of the remaining time, and putting the test and the perror() within the loop to print all possible errors from nanosleep. No matter what I do, I always receive an EINVAL from the first call to nanosleep()
So, there seems to be a real problema with nanosleep() on WSL. See https://github.com/microsoft/WSL/issues/4898 . It mentions a problem for WSL being unable to read the realtime clock from a certain version of glibc. I tried this in my WSL terminal:
$ sleep 1
sleep: cannot read realtime clock: Invalid argument
There is a mention of a workaround here:
https://github.com/microsoft/WSL/issues/4898#issuecomment-612622828
I've tried with another approach: using clock_nanosleep() so I can choose another source for the clock: in the above program, just change the call to nanosleep() with this other to clock_nanosleep()
clock_nanosleep (CLOCK_MONOTONIC, 0, &req, &rem);
There is no problem with CLOCK_MONOTONIC, and now the program works!

Getting file time using stat & tm structor in Linux

I using g++ on linux with eclipse. I am making a code that get file's time and output file's month,hour,etc...
While debugging, the value of time1 changed unexpectedly but I have no idea about this issue.
What is problem of this code?
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
struct stat stat1, stat2;
struct tm *time1, *time2;
void filestat1(void);
void filestat2(void);
void filetime1(void);
void filetime2(void);
void datecmp(void);
void timecmp(void);
int main(void)
{
filestat1();
filestat2();
filetime1();
filetime2();
datecmp();
timecmp();
}
void filestat1(void)
{
// check if there is no text1
int check = 0;
check = stat("text1", &stat1);
if(check != 0)
{
printf("Error : there is no text1\n");
}
return;
}
void filestat2(void)
{
// check if there is no text2
int check = 0;
check = stat("text2", &stat2);
if(check != 0)
{
printf("Error : there is no text2\n");
}
return;
}
void filetime1(void)
{
time1 = localtime(&stat1.st_mtime); //!!! this change unexpectedly
return;
}
void filetime2(void)
{
time2 = localtime(&stat2.st_mtime);
return;
}
void datecmp(void)
{
printf("date compare\n");
// compare tm_mon
if(time1->tm_mon > time2->tm_mon)
printf("time1 is early \n");
else if(time1->tm_mon < time2->tm_mon)
printf("time2 is early \n");
else{
// compare tm_mday
if(time1->tm_mday > time2->tm_mday)
printf("time1 is early \n");
else if(time1->tm_mday < time2->tm_mday)
printf("time2 is early \n");
// same date
else
printf("same time \n");
}
printf("\n");
}
void timecmp(void)
{
printf(time1->tm_hour);
printf(time2->tm_hour);
printf("time compare\n");
// compare hour
if(time1->tm_hour > time2->tm_hour)
printf("time1 is early \n");
else if(time1->tm_hour < time2->tm_hour)
printf("time2 is early \n");
else{
// compare minutes
if(time1->tm_min > time2->tm_min)
printf("time1 is early \n");
else if(time1->tm_min < time2->tm_min)
printf("time2 is early \n");
// same time
else
printf("same time \n");
}
}
localtime returns a pointer to a static structure. You need to copy the result before calling localtime again.
I would declare time1 and time2 as structures instead of pointers to store the values.
struct tm time1, time2;
void filetime1(void)
{
struct tm *tmp = localtime(&stat1.st_mtime);
if (tmp == NULL) {
//... handle error
}
time1 = *tmp;
}
Similarly for filetime2.
If you are writing multi-threaded code, it is safer to use the reentrant variant of the function, localtime_r. In that case, you pass in the pointer to the structure for the result.
void filetime1(void)
{
struct tm *tmp = localtime_r(&stat1.st_mtime, &time1);
if (tmp == NULL) {
//... handle error
} else {
assert(tmp == &time1);
}
}
You are using global variables, completely unnecessarily, making your life harder than it has to be. It is very hard for us humans to track where global variables are modified, especially when you have several global variables with very similar names.
So, instead of trying to unravel all that, let's rewrite it using function parameters, without any global variables at all.
First, we tell the C library we want POSIX.1-2008 features, and include the headers that expose the functionality we need:
#define _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <limits.h>
#include <time.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
Next, let's define a function that takes a file name as a parameter, and pointers to where the function can store the last access and last modification timestamps. If the function is successful, it'll return 0; otherwise, it'll return -1 with errno set to indicate the error.
int filetime(const char *path,
time_t *accessed, long *accessed_nsec,
time_t *modified, long *modified_nsec)
{
struct stat info;
/* Path must not be NULL or empty. */
if (!path || !path[0]) {
errno = EINVAL;
return -1;
}
/* Get file statistics. */
if (stat(path, &info) == -1)
return -1; /* errno was set by stat() */
/* Save timestamps. */
if (accessed)
*accessed = info.st_atim.tv_sec;
if (accessed_nsec)
*accessed_nsec = info.st_atim.tv_nsec;
if (modified)
*modified = info.st_mtim.tv_sec;
if (modified_nsec)
*modified_nsec = info.st_mtim.tv_nsec;
/* Success. */
return 0;
}
Let's continue by writing a simple main(), that takes one or more file names as command-line parameters, and describes them. I like to start the main by checking the number of command line arguments, and if specified, the first argument. If none, or the first one is -h or --help, I like to print the usage of the utility. This way, I can keep my example programs in their own directories, and to find one I'm looking for, I can just execute each one without parameters, to see what each of them does. It's much faster than reading the sources!
int main(int argc, char *argv[])
{
int arg;
if (argc < 2 || !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
fprintf(stderr, "\n");
fprintf(stderr, "Usage: %s [ -h | --help ]\n", argv[0]);
fprintf(stderr, " %s FILENAME ...\n", argv[0]);
fprintf(stderr, "\n");
fprintf(stderr, "This program will print the last access and\n");
fprintf(stderr, "last modification timestamps for each of\n");
fprintf(stderr, "the specified files.\n");
fprintf(stderr, "\n");
return EXIT_FAILURE;
}
Because there is at least one, but possibly more than one file name parameter, we handle each of them in a loop:
for (arg = 1; arg < argc; arg++) {
time_t accessed, modified;
long accessed_ns, modified_ns;
struct tm accessed_localtime, modified_localtime;
Within the loop, we first call our filetime() function. Note how we have declared the variables we want filled above, and how we call the function: &accessed yields a pointer to accessed.
if (filetime(argv[arg], &accessed, &accessed_ns,
&modified, &modified_ns)) {
/* Nonzero return value, so an error occurred! */
fprintf(stderr, "%s: %s.\n", argv[arg], strerror(errno));
return EXIT_FAILURE;
}
In C, function parameters are passed by value, not by reference. This means that if a function parameter is say int foo, any changes to foo within the function are visible within the function only; the changes are not visible to the caller. When we pass a pointer to a variable, say int *foo, then changes to foo are still visible only within the function, but *foo refers to the value pointed at by the pointer; and changes to that are visible to the caller.
In short, when we want a function to be able to modify the value of a variable, we use a pointer. That's just how C works.
Now that we have the times in Unix Epoch time (time_t), we want to split them into local time fields:
if (!localtime_r(&accessed, &accessed_localtime) ||
!localtime_r(&modified, &modified_localtime)) {
fprintf(stderr, "%s: Cannot compute timestamps in local time: %s.\n", argv[arg], strerror(errno));
return EXIT_FAILURE;
}
Note that I again used a POSIX.1-2008 function, localtime_r(). In tutorials, you often see the older localtime() used instead, but that one may use a global variable internally (it can always return a pointer to the same structure, reusing it for every call); localtime_r() is better.
See how the second parameter to localtime_r is also a pointer (to a struct tm)? Again, this is just how you do functions that change some values in a way that is visible to the caller.
Also, it is rare for localtime_r() (or localtime()) to fail, so many simply ignore checking it for errors. There is no excuse for that, as it's just a couple of lines more code, and if an error does occur at some point, the user will be immensely more satisfied with a clear error code, rather than just seeing the program crash due to segmentation fault.
All that is left, is to print out the information gathered. I like to use a variant the ISO 8601 international standard for the time format; in particular, it sorts in proper time order even if sorted alphabetically. (My variant is that I like to use a space, and not a T, between the date and the time.)
printf("%s:\n", argv[arg]); /* The file name or path */
printf(" Modified: %04d-%02d-%02d %02d:%02d:%02d.%03d\n",
modified_localtime.tm_year + 1900,
modified_localtime.tm_mon + 1,
modified_localtime.tm_mday,
modified_localtime.tm_hour,
modified_localtime.tm_min,
modified_localtime.tm_sec,
modified_ns / 1000000L);
printf(" Accessed: %04d-%02d-%02d %02d:%02d:%02d.%03d\n",
accessed_localtime.tm_year + 1900,
accessed_localtime.tm_mon + 1,
accessed_localtime.tm_mday,
accessed_localtime.tm_hour,
accessed_localtime.tm_min,
accessed_localtime.tm_sec,
accessed_ns / 1000000L);
/* Make sure everything written to stdout
is actually written to standard output right now. */
fflush(stdout);
}
return EXIT_SUCCESS;
}
The fflush(stdout) tells the C library to ensure all preceding writes to stdout are actually written to the standard output. (By default, stdout is buffered, and stderr is unbuffered.) Normally, the C library will flush the output at every newline, but having the explicit flush there also reminds us human programmers that we want everything thus far printed, to actually appear on the programs standard output at that point. (This way, if one of the files is on some slow filesystem, say old USB stick or a network share, the information on previous files gets shown before the program accesses the slow file. Essentially, the "stall" will occur at the expected place for the human users.)
It is probably a good idea to mention relatime and other related mount options at this point. In simple terms, it means that to avoid the number of writes to storage media due to read accesses, the access time is not always updated. So, if you don't see it changing even after you read a file (using e.g. cat FILENAME >/dev/null), it just means your system has mount options enabled that reduce the access time updates to speed up your filesystem access and reduce the number of writes to it. It is a good option; I use it.
Finally, most Linux filesystems do not have a created timestamp at all. The st_ctime (and st_ctim.tv_sec and st_ctim.tv_nsec) fields refer to last status change timestamp. It tracks changes to the owner, group, permissions, and the number of hard links.
When you examine the above code, especially the if clauses, it is useful to remember that in C, the logical OR operation, ||, is short-circuiting: the left side is evaluated first, but if it fails, the right side is not evaluated at all. So, if you have e.g. int x = 1, y = 0; and you do (x == 0 || ++y), y will not be incremented at all. I utilize this when examining argv[1] in the very first if clause in main().

What costs the extra execution time of the routine in a pthread program?

I wrote four different programs to count total words in two files. These four versions look mostly the same. First three versions use two threads to count and just the orders of three statements are different. The last version uses one thread to count. I will list the different part of each version and the common part first, then the output of each version and my question.
different part:
// version 1
count_words(&file1);
pthread_create(&new_thread, NULL, count_words, &file2);
pthread_join(new_thread, NULL);
// version 2
pthread_create(&new_thread, NULL, count_words, &file2);
count_words(&file1);
pthread_join(new_thread, NULL);
// version 3
pthread_create(&new_thread, NULL, count_words, &file2);
pthread_join(new_thread, NULL);
count_words(&file1);
// version 4
count_words(&file1);
count_words(&file2);
common part: (Insert the different part into this common part to make a complete version)
#include <stdio.h>
#include <pthread.h>
#include <ctype.h>
#include <stdlib.h>
#include <time.h>
#define N 2000
typedef struct file_t {
char *name;
int words;
} file_t;
double time_diff(struct timespec *, struct timespec *);
void *count_words(void *);
// Usage: progname file1 file2
int main(int argc, char *argv[]) {
pthread_t new_thread;
file_t file1, file2;
file1.name = argv[1];
file1.words = 0;
file2.name= argv[2];
file2.words = 0;
// Insert different part here
printf("Total words: %d\n", file1.words+file2.words);
return 0;
}
void *count_words(void *arg) {
FILE *fp;
file_t *file = (file_t *)arg;
int i, c, prevc = '\0';
struct timespec process_beg, process_end;
struct timespec thread_beg, thread_end;
double process_diff, thread_diff;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &process_beg);
clock_gettime(CLOCK_THREAD_CPUTIME_ID, &thread_beg);
fp = fopen(file->name, "r");
for (i = 0; i < N; i++) {
while ((c = getc(fp)) != EOF) {
if (!isalnum(c) && isalnum(prevc))
file->words++;
prevc = c;
}
fseek(fp, 0, SEEK_SET);
}
fclose(fp);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &process_end);
clock_gettime(CLOCK_THREAD_CPUTIME_ID, &thread_end);
process_diff = time_diff(&process_beg, &process_end);
thread_diff = time_diff(&thread_beg, &thread_end);
printf("count_words() in %s takes %.3fs process time and"
"%.3fs thread time\n", file->name, process_diff, thread_diff);
return NULL;
}
double time_diff(struct timespec *beg, struct timespec *end) {
return ((double)end->tv_sec + (double)end->tv_nsec*1.0e-9)
- ((double)beg->tv_sec + (double)beg->tv_nsec*1.0e-9);
}
NOTE
file1 is a file with 10000 words of "word". file2 is a copy of file1, created by cp command.
To make the execution time long enough, program repeatly counts the words. N is the number of loops. So the result is not the accurate number of total words, but that multiplies by N.
Please don't put too much emphasis on the counting algorithm. I am just concerned about the execution time in this example.
An important information: The machine is IntelĀ® Celeron(R) CPU 420 # 1.60GHz. one core. The OS is Linux 3.2.0. Maybe one core is the cause of this strange phenomenon like others said. But I still want to figure it out.
The program counts words and uses clock_gettime() to calculate the process cpu time and the thread cpu time of routine count_words() and then output the times and the word number. Below is the output and my comment with questions. I will be very appreciated if someone can explain the reason what the extra time is taken on.
// version 1
count_words() in file1 takes 2.563s process time and 2.563s thread time
count_words() in file2 takes 8.374s process time and 8.374s thread time
Total words: 40000000
Comment: The original thread finishes count_words() and waits for the new thread to die. When count_words() running in the new thread, no context switch happens (because process time == thread time). Why it takes so much time? What happens in count_words() in the new thread?
// version 2
count_words() in file1 takes 16.755s process time and 8.377s thread time
count_words() in file2 takes 16.753s process time and 8.380s thread time
Total words: 40000000
Comment: Two threads parallel runs here. Context switch happens, so the process time > thread time.
// version 3
count_words() in file2 takes 8.374s process time and 8.374s thread time
count_words() in file1 takes 8.365s process time and 8.365s thread time
Total words: 40000000
Comment: New thread counts first and original thread waits for it. After new thread is joined, original thread begins to count. Neither of them has context switching, why so much time taken, especially the count after the new thread joined?
// version 4
count_words() in file1 takes 2.555s process time and 2.555s thread time
count_words() in file2 takes 2.556s process time and 2.556s thread time
Total words: 40000000
Comment: Fastest version. No new thread created. Both count_words() runs in a single thread.
It's probably because creation of any thread forces libc to use synchronization in getc. This makes this function significantly slower. Following example is for me as slow as version 3:
void *skip(void *p){ return NULL; };
pthread_create(&new_thread, NULL, skip, NULL);
count_words(&file1);
count_words(&file2);
To fix this problem you can use a buffer:
for (i = 0; i < N; i++) {
char buffer[BUFSIZ];
int read;
do {
read = fread(buffer, 1, BUFSIZ, fp);
int j;
for(j = 0; j < read; j++) {
if (!isalnum(buffer[j]) && isalnum(prevc))
file->words++;
prevc = buffer[j];
}
} while(read == BUFSIZ);
fseek(fp, 0, SEEK_SET);
}
In this solution, IO functions are called rarely enough to make synchronization overhead insignificant. This not only solves problem of weird timings, but also makes it several times faster. For me it's reduction from 0.54s (without threads) or 0.85s (with threads) to 0.15s (in both cases).

How to control execution time in C

I have a C program which will print the prime numbers into a .txt file.
I want program to ask me the execution time by minutes. Trying to solve with the piece of code.
#include <stdio.h>
#include <time.h>
int main()
{
execute();
return(0);
}
int execute(int minute)
{
time_t now;
time(&now);
struct tm *tmp = localtime(&now);
printf("How long you want to execute the program by minute? ");
scanf("%d",&minute);
printf("%d %02d %02d\n",tmp->tm_hour, tmp->tm_min+minute, tmp->tm_sec);
return(minute);
}
and here also is the code that I want to run.
#include <stdio.h>
int isprime(int x);
int main(void)
{
int AX_REGISTER, BX_REGISTER;
FILE *number, *primes;
int forever = 1;
while (forever)
{
if ((number = fopen("lastnumber.txt", "r")) == NULL)
{
fprintf(stderr, "Cannot read LASTNUMBER.txt file.\n");
return 1;
}
fscanf(number,"%d",&AX_REGISTER);
fclose(number);
BX_REGISTER=AX_REGISTER;
AX_REGISTER=AX_REGISTER+1;
if ((number = fopen("lastnumber.txt", "w")) == NULL)
{
fprintf(stderr, "Cannot write LASTNUMBER.txt file.\n");
return 1;
}
fprintf(number,"%d\n",AX_REGISTER);
fclose(number);
if (isprime(BX_REGISTER))
{
if ((primes = fopen("primes.txt", "a")) == NULL)
{
fprintf(stderr, "Cannot open PRIMES.txt file.\n");
return 1;
}
fprintf(primes,"%d\n",BX_REGISTER);
fclose(primes);
}
}
return 0;
}
int isprime(int x)
{
int i;
for (i=2;i<x;i++)
{
if (x%i==0)
return 0;
}
return 1;
}
Since I am a newbie in C programming language I can not solve it by myself. Can someone help me?
Some platforms have an alarm() function that you can use to send a signal to your application after a specified number of seconds.
If you're not on Windows, man alarm should give you some information about this function. If you're on Windows, a different approach may be needed.
On another note, you should consider using variable names that mean something to the code you're writing. To a casual reader, the name BX_REGISTER means nothing. Perhaps consider changing its name to number_to_test (and AX_REGISTER to next_number or something).
Since you are running in a while loop, simply get the current time outside the while loop, add the minutes, and also get the time at the end of the while loop. Something like:
time_t now;
time_t end_time;
now = time();
end_time = now + (minutes * 60);
while(now < end_time)
{
...Do processing here...
now = time();
}
One drawback of this method is that if isprime() takes a very very long time to run then you may overshoot the end time by quite a lot. One way to solve that is to pass the end_time value to isprime() and check it on the loop in that function too. Or just press Ctrl-C in the terminal where you are running the program :)
By all means write to the files in case the program crashes - you won't want to lose hours of work, but I suggest you only read the value from lastnumber.txt before the while loop and after that just hold it in memory. It will speed up your programs.
Also, unless running on Windows which has horrible file locking semantics, it may be worth holding the write file handles open the whole time to save cycles constantly opening and closing the files.

system time setting using c library function

I can get the system time using struct tm and time(),localtime(),asctime().but i need help about how i can set time of system using c program.
if you don't want to execute a shell command you can (as you mentioned) use the settimeofday, i would start by reading the MAN page, or looking for some examples
here's an example:
#include <sys/time.h>
#include <stdio.h>
#include <errno.h>
int main(int argc, char *argv[])
{
struct timeval now;
int rc;
now.tv_sec=866208142;
now.tv_usec=290944;
rc=settimeofday(&now, NULL);
if(rc==0) {
printf("settimeofday() successful.\n");
}
else {
printf("settimeofday() failed, "
"errno = %d\n",errno);
return -1;
}
return 0;
}
Shamelessly ripped From IBMs documentation, the struct timeval struct holds the number of seconds (as a long) plus the number of microseconds (as a long) from 1 January 1970, 00:00:00 UTC (Unix Epoch time). So you will need to calculate these numbers in order to set the time. you can use these helper functions, to better handle dealing with the timeval struct.

Resources