Friday, February 17, 2023

NAWK: How can I get uptime & boot time in Solaris?

 

[Solaris Logo, courtesy former Sun Microsystems, Oracle]

Abstract:

This is part of a small article series on lesser known uses of UNIX nawk. Why nawk? This POSIX language has not changed in decades, gets very few code changes, and is mostly bug free in any reasonable operating system. Scripts written in POSIX nawk will basically run, forever. Master this simple language, and there is virtually nothing that can not be done.

What is AWK?

Awk is a scriptable text language, originally written by the authors of UNIX and C: Alfred Aho, Peter Weinberger, and Brian Kernighan. It's concepts are managing Page Header (the BEGIN clause), Page Body (multiple Pattern -> Action clauses), and Page Footer (the END clause.) 

Awk is suitable for building & manipulating any textual or markup text, which is page oriented (i.e. SQL output, Text, Adobe PostScript, Adobe FrameMaker portable maker format, HTML, XML, Microsoft RTF, Microsoft CSV, etc.)

NAWK: How can I get uptime & boot time in Solaris?

The CTime or Epoch Time can be easily retrieved from nawk using the "srand()" function, if there is no seed passed into the function. This number represents the seconds since 00:00:00 on January 1, 1970.

The boot time is the CTime/Epoch Time [in seconds], at the time of the last OS boot, and can be retrieved from "kstat". Simple subtraction and division can provide reasonably accurate conversions.

The following examples show: CTime, Boot Time, Seconds Difference, Minutes Difference, Hours Difference, Days Difference.

Example 1 - Solaris 10:

Solaris10/root# kstat -n system_misc | nawk '
BEGIN { CTime=srand() };
/boot_time/ { BTime=$2; Diff=CTime-BTime };
END { printf "CTime:\t%s\nBTime:\t%s\nScDif:\t%s\nMnDif:\t%s\nHrDif:\t%s\nDyDif:\t%s\n",
      CTime,BTime,Diff,Diff/60,Diff/60/60,Diff/60/60/24 }'

CTime:  1676683570
BTime:  1676106161
ScDif:  577409
MnDif:  9623.48
HrDif:  160.391
DyDif:  6.68297

Example 2 - Solaris 11:

Solaris 11/root# kstat -n system_misc | nawk '
BEGIN { CTime=srand() };
/boot_time/ { BTime=$2; Diff=CTime-BTime };
END { printf "CTime:\t%s\nBTime:\t%s\nScDif:\t%s\nMnDif:\t%s\nHrDif:\t%s\nDyDif:\t%s\n",
      CTime,BTime,Diff,Diff/60,Diff/60/60,Diff/60/60/24 }'

CTime:  1676683533
BTime:  1662691183
SecDif: 13992350
MinDif: 233206
HrDif:  3886.76
DayDif: 161.948

Does the code look similar? It should, Solaris 10 and Solaris 11 are POSIX compliant.

What about GAWK?

GNU's Awk is not 100% compatible with POSIX Nawk, which is a huge disappointment. I have seen code, which worked for decades, never able to run unchanged under GNU's awk.

 

No comments:

Post a Comment