[GNU Manual] [No POSIX requirement] [Linux man] [FreeBSD man]
Summary
uptime - show how long the system has been running
Lines of code: 264
Principal syscall: None (ignoring file reading)
Support syscalls: None
Options: 0 (help and version embedded in to usage)
Added to Shellutils in July 1997 [First version]
Number of revisions: 100 [Code Evolution]
The uptime utility relies on the utmpx data structure for calculating uptime. The data structure is well-defined, but location and access method is system dependent.
Helpers:print_uptime()
- Prints data from utmp bufferuptime()
- Accesses utmp file and requests printing
read_utmp()
- Copies utmpx data in to provided buffer
Setup
uptime has no options but accepts an optional path to a utmp file
main() initializes no extra variables:
Parsing
Parsing for uptime checks for an argument assumed to be a path to a utmp file.
Execution kicks off with a call to uptime()
using either the default or user-supplied utmp file.
Parsing failures
These failure will fail if there are any options or more than one argument
Execution
POSIX compliant systems include data structures to calculate uptime, user count, and load, but implementations vary. The first task is to find the boot time:
- Procps systems (Linux) - Open
/proc/uptime
, get the number of up seconds, and close the file - Sysctl systems (FreeBSD) - Pull boot time with sysctl using the CTL_KERN and KERN_BOOTTIME fields
- BeOS - Pull the boot_time field using
get_system_info
The boot time is compared with the current time for the total uptime.
For the user count, loop through the utmp entries and count.
System load averages are calculated on Linux systems with getloadavg
, although this function is not part of POSIX.
All calculated data is output on a single line using printf()
Failure case:
- Boot time unavailable
All failures at this stage output an error message to STDERR and return without displaying usage help