Advertisement
Sonikku1980

Shell Programming - Write a program called collect users

Mar 30th, 2015
268
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.34 KB | None | 0 0
  1. #!/bin/bash
  2. #This program runs in the background and counts the number of users logged in
  3. #at the end of each interval and also the number of processes run during that
  4. #interval.
  5. if [ $# -eq 0 ]; then
  6.         echo "usage: `basename $0` -t time | time" >&1; exit 2
  7. elif [ "$1" = "-t" ]; then
  8.         if [ $# -eq 2 ]; then
  9.                 time="$2"
  10.         else
  11.                 time=600
  12.         fi
  13. else
  14.         time="$1"
  15. fi
  16. if [ "$time" -lt 0 ]; then
  17.     echo "Invalid argument: $time" >&2; exit 2
  18. fi
  19. function do_ps {
  20.         ps -a | awk '$1 != "PID" && $1 != 1 { print $1 }' | sort -u >$1
  21. }
  22. newfile=/tmp/file1.$$
  23. oldfile=/tmp/file2.$$
  24. trap "rm -f $newfile $oldfile; exit 1" 2 3 15
  25. let time=$((`date +%s`+$time))
  26. do_ps $oldfile
  27. back=$!
  28. while [ `date +%s` -le ${time} ]; do
  29.         do_ps $newfile
  30.         #check for foreground processes
  31.         if [ $((tmp=`diff $newfile $oldfile | grep -c "^<"`)) -ge 1 ]; then
  32.                 let count+=${tmp}
  33.                 tmp=$oldfile
  34.                 oldfile=$newfile
  35.                 newfile=$tmp
  36.         fi
  37.         #check for background processes
  38.         if [ ${back} -ne $! ]; then
  39.                 let count+=1
  40.                 back=$!
  41.         fi
  42.         sleep 1
  43. done
  44. echo There were $count processes running
  45. echo There were `who | uniq | wc -l` users on the system
  46. rm $oldfile
  47. rm $newfile
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement