tags:

views:

93

answers:

3

From a C++ app. compiled for AIX, HP-UX, Linux, OSX and Solaris is there a simple way to determine whether the app. is running within 5 minutes of system boot?

On Windows I can do this:

// return true if OS has recently booted up
bool at_os_boot_time()
{
    /*  GetTickCount() returns the number of miliseconds since system start.
        So "...the time will wrap around to zero if the system is run 
        continuously for 49.7 days" - so this function will erroneously 
        return true for a 5 minute period 49.7 days after boot */
    return ::GetTickCount() < 5 * 60 * 1000;
}

I can't find the equivalent in the Unix world.

+2  A: 

At least in Linux you can use the sysinfo system call.

Joachim Sauer
+2  A: 

this is from kernel.h on linux:

struct sysinfo;
extern int do_sysinfo(struct sysinfo *info);

#endif /* __KERNEL__ */

#define SI_LOAD_SHIFT   16
struct sysinfo {
    long uptime;            /* Seconds since boot */
    unsigned long loads[3];     /* 1, 5, and 15 minute load averages */
    unsigned long totalram;     /* Total usable main memory size */
    unsigned long freeram;      /* Available memory size */
    unsigned long sharedram;    /* Amount of shared memory */
    unsigned long bufferram;    /* Memory used by buffers */
    unsigned long totalswap;    /* Total swap space size */
    unsigned long freeswap;     /* swap space still available */
    unsigned short procs;       /* Number of current processes */
    unsigned short pad;     /* explicit padding for m68k */
    unsigned long totalhigh;    /* Total high memory size */
    unsigned long freehigh;     /* Available high memory size */
    unsigned int mem_unit;      /* Memory unit size in bytes */
    char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding: libc5 uses this.. */
};
Omry
A: 

The most portable method to determine the time of the last system boot is to use getutxid(), with a ut_type of BOOT_TIME, to get it using the system accounting data. I think that all of the systems you mentioned should support this, although it may not be particularly efficient. You could also call a command line program like uptime, who -b, or w.

Some systems support a more efficient interface to get this information but it will be OS-specific. Mac OS X (and FreeBSD) has the sysctl() CTL_KERN KERN_BOOTTIME. HP-UX has pstat_getstatic(). Tru64 has table() with the TBL_SYSINFO parameter. As mentioned in another answer Linux has sysinfo(), but you can also read the time since boot from from /proc/uptime (it is the first number).

mark4o
Very helpful answer. Thank you.
Ant