Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a whattime.c program which accepts either a “-f” or “-d” argument or no ar

ID: 3686704 • Letter: W

Question

Write a whattime.c program which accepts either a “-f” or “-d” argument or no arguments at all. If the program is run with either no arguments or the “-f” argument, then the program runs in the foreground and outputs it's results to stdout. If “-d” is given when the program is run, then it immediately becomes a daemon and runs in the background (detached from any terminals) and logs to a file called mydeamon.log. Whether the program runs in the foreground or background doesn't matter, the program should always run for one minute. Every two seconds your program should re port the number of seconds since 1/1/1970 12:00am and also the username and home directory of the user who started the program up (refer to getenv function in stdlib.h). And by “report” I mean if you run in the foreground, then display the results to stdout, if run as a daemon, then output to the log file.

Explanation / Answer

whattime.h

#ifndef PROC_WHATTIME_H
#define PROC_WHATTIME_H

EXTERN_C_BEGIN

extern void print_uptime(void);
extern char *sprint_uptime(void);

EXTERN_C_END

#endif


whattime.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <utmp.h>
#include <sys/ioctl.h>
#include "whattime.h"
#include "sysinfo.h"

static char buf[128];
static double av[3];

char *sprint_uptime(void) {
struct utmp *utmpstruct;
int upminutes, uphours, updays;
int pos;
struct tm *realtime;
time_t realseconds;
int numuser;
double uptime_secs, idle_secs;


time(&realseconds);
realtime = localtime(&realseconds);
pos = sprintf(buf, " %02d:%02d:%02d ",
realtime->tm_hour, realtime->tm_min, realtime->tm_sec);

uptime(&uptime_secs, &idle_secs);

updays = (int) uptime_secs / (60*60*24);
strcat (buf, "up ");
pos += 3;
if (updays)
pos += sprintf(buf + pos, "%d day%s, ", updays, (updays != 1) ? "s" : "");
upminutes = (int) uptime_secs / 60;
uphours = upminutes / 60;
uphours = uphours % 24;
upminutes = upminutes % 60;
if(uphours)
pos += sprintf(buf + pos, "%2d:%02d, ", uphours, upminutes);
else
pos += sprintf(buf + pos, "%d min, ", upminutes);


numuser = 0;
setutent();
while ((utmpstruct = getutent())) {
if ((utmpstruct->ut_type == USER_PROCESS) &&
(utmpstruct->ut_name[0] != ''))
numuser++;
}
endutent();

pos += sprintf(buf + pos, "%2d user%s, ", numuser, numuser == 1 ? "" : "s");

loadavg(&av[0], &av[1], &av[2]);

pos += sprintf(buf + pos, " load average: %.2f, %.2f, %.2f",
       av[0], av[1], av[2]);

return buf;
}

void print_uptime(void) {
printf("%s ", sprint_uptime());
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote