Topic: C/C++: Continuously read a file

I'm working on a server which should continously read a file and send it to a bunch of clients. The server <-> client thing works fine, but the file-reading is not. How do I read the file without the program raking 100% CPU?

The file is a log from another server, so it's actually "endless".

Re: C/C++: Continuously read a file

You can make it check for something new every 5 mins or something. Maybe there is a better solution but it would work :)

Re: C/C++: Continuously read a file

You have to tell the operating system that you won't be using the processor for a while. You do that by putting your thread to sleep for a few milliseconds. I'm not sure how to do that in C++ though. Someone else will have to answer that :-)

"Programming is like sex: one mistake and you have to support it for the rest of your life."

4 (edited by sverrir 2004-04-19 02:23)

Re: C/C++: Continuously read a file

Here is a thread program I did for a course in operating systems.
I think it should answear your questions on how to handle the sleep issue.

#include <windows.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <process.h>
#include <iostream.h>
#include <conio.h>

static int runFlag = TRUE;

DWORD WINAPI threadWork(LPVOID threadNo)
{
    double y;
    const double x = 3.14159;
    const double e = 2.7183;
    int i;
    const int napTime = 1000; 
    const int busyTime = 40000;
    DWORD result = 0;
    
    while(runFlag)
    {
        for(i = 0; i < busyTime; i++)
            y = pow(x, e);                
        Sleep(napTime);
        cout << "Thread Awake" << endl;
    }
    return result;
}

//*******************************************************************************************************//

int main(int argc, char* argv[])
{    
    if(argc<3)   //number of threads and time
    {
        //cout translates to: Error, you can only use 2 variables(nr. of threads & time)
                cout<< "Villa, thu matt adeins nota 2 faeribreytur (fjoldi & timi)!"<< endl;
        getch();
        return 0;
    }

    int fjoldi_thrada;                    //number_of_threads
    unsigned int runTime;
    fjoldi_thrada = atoi(argv[1]);
    runTime = atoi(argv[2]);

    SYSTEMTIME now;
    WORD stopTimeMinute, stopTimeSecond;

    GetSystemTime(&now);

    cout<<"mthread: Suite starting at system time: "<<now.wHour<<":"<<now.wMinute<<":"<<now.wSecond<<endl;
    stopTimeSecond = (now.wSecond + (WORD) runTime) & 60;
    stopTimeMinute = now.wMinute + (now.wSecond + (WORD) runTime) /60;
    
    int arg;

    DWORD targetThreadID;

    for(int i = 0; i < fjoldi_thrada; i++)
    {
        _beginthreadex(NULL, 0, (unsigned(_stdcall *)(void*))threadWork, &arg,0,(unsigned *) &targetThreadID);
        Sleep(100);
        cout << "Process Awake" << endl;
    }


    while(runFlag)
    {
        cout << "Check" << endl;

        GetSystemTime(&now);
        if((now.wMinute >= stopTimeMinute) && (now.wSecond >= stopTimeSecond))
            runFlag = FALSE;
            Sleep(1000);    
    }
        cout << "Sleep" << endl;
        Sleep(5000);
        getch();
        return 0;
}

Re: C/C++: Continuously read a file

Jansson wrote:

You can make it check for something new every 5 mins or something. Maybe there is a better solution but it would work :)

Yeay, I thought of that too. Maybe use fopen/fseek each second and send all new lines. But then I need a timer :)

sverrir wrote:

Here is a thread program I did for a course in operating systems.
I think it should answear your questions on how to handle the sleep issue.

...

Great! I'll have a look at it when I'm home from school.

6 (edited by sverrir 2004-04-19 11:26)

Re: C/C++: Continuously read a file

Timer

<?php
function ss_timing_start ($name = 'default') {
    global $ss_timing_start_times;
    $ss_timing_start_times[$name] = explode(' ', microtime());
}
function ss_timing_stop ($name = 'default') {
    global $ss_timing_stop_times;
    $ss_timing_stop_times[$name] = explode(' ', microtime());
}

function ss_timing_current ($name = 'default') {
    global $ss_timing_start_times, $ss_timing_stop_times;
    if (!isset($ss_timing_start_times[$name])) {
        return 0;
    }
    if (!isset($ss_timing_stop_times[$name])) {
        $stop_time = explode(' ', microtime());
    }
    else {
        $stop_time = $ss_timing_stop_times[$name];
    }
    // do the big numbers first so the small ones aren't lost
    $current = $stop_time[1] - $ss_timing_start_times[$name][1];
    $current += $stop_time[0] - $ss_timing_start_times[$name][0];
    return $current;
}
?>

The program

<?php
require_once('timer.php');    
    
  ss_timing_start();
    //Some programing done here :)
  ss_timing_stop();

echo 'Program execution: '.ss_timing_current().'  seconds';
?>

Re: C/C++: Continuously read a file

sverrir wrote:

Timer

...

The program

...

One problem with this code... I'm making the program in C/C++ :)

8 (edited by sverrir 2004-04-19 18:25)

Re: C/C++: Continuously read a file

Hehe, my bad, have to sleep some more wink
You should be able to use "GetSystemTime, stopTime" from my other example.

Re: C/C++: Continuously read a file

sverrir wrote:

Hehe, my bad, have to sleep some more ;)
You should be able to use "GetSystemTime, stopTime" from my other example.

Yah, I solved the problem uring sleep(int seconds) =) Easy solution! But with one problem solved, another one comes along: I must send the data to all clients...

Re: C/C++: Continuously read a file

Does someone know how much pointers and such stuff a child and a parent shares? The program should fork, and the child handle the file (sending it), and the parent all the connections.

The problem is that the child don't know which connections that are active =/ Can someone see what's wrong? (The code around "printf(" >> %d", i);" in the child outputs only the process id (3), and the parent outputs all connections (as the child should do also)).

...includes, process() and checkpasswd()...

int main (int argc, char **argv){

    ...alot of init code...

    // Initialize the active sockets
    FD_ZERO (&master);
    FD_ZERO (&read_fds);
    FD_SET (sock, &master);

    if( fork() == 0 ){
        // Child process    
        ...
        printf("Child!\n");

        // Open the file
        pos = 0;
        while(true){

            read_fds = master;
            printf("Child sockets:");
            for( i = 0; i < FD_SETSIZE; i++){
                if (FD_ISSET (i, &read_fds) > 0)
                    printf(" >> %d", i);           <----------------------
            }
            printf("\n");

            // Sleep for a while
            sleep(2);
        }

        printf("No more child =(\n");

        fclose(fp);
        exit(0);
    }

    else{
        // Parent process

        while (true){
            read_fds = master;

            printf("Active sockets:");
            for( i = 0; i < FD_SETSIZE; i++){
                if (FD_ISSET (i, &read_fds) && i != sock)
                    printf(" >> %d", i);            <----------------------
            }
            printf("\n");

            // Wait for an active socket
            printf("\nWaiting...\n");
            if (select (FD_SETSIZE, &read_fds, NULL, NULL, NULL) < 0){
                perror ("Select error");
                exit(1);
            }

            // Loop through all sockets
            for (i = 0; i < FD_SETSIZE; i++){

                if (FD_ISSET (i, &read_fds)){

                    // Got a new connection on the original socket
                    if (i == sock){
                        ...FD_SET...
                    }

                    // Data arriving on an "old" socket -> process the data
                    else{
                        ...
                    } // end if (i==sock)

                } // end if (FD_ISSET)

            } // end for (FD_SETSIZE)

        } // inf loop

    } // end (fork)

    close(sock);
    return(0);

}

... I doubt anyone understand what I want though... should sleep instead.