ptg10805159
Appendix C Chapter 13 Solutions 929
#include <unistd.h>
#include <time.h>
#include <sys/select.h>
unsigned
sleep(unsigned seconds)
{
int n;
unsigned slept;
time_t start, end;
struct timeval tv;
tv.tv_sec = seconds;
tv.tv_usec = 0;
time(&start);
n=select(0, NULL, NULL, NULL, &tv);
if (n == 0)
return(0);
time(&end);
slept = end - start;
if (slept >= seconds)
return(0);
return(seconds - slept);
}
Figure C.13 Athread-safe implementation ofsleep
13.3 FigureC.14 shows a solution.
#include "apue.h"
int
main(void)
{
FILE *fp;
char *p;
daemonize("getlog");
p=getlogin();
fp = fopen("/tmp/getlog.out", "w");
if (fp != NULL) {
if (p == NULL)
fprintf(fp, "no login name\n");
else
fprintf(fp, "login name: %s\n", p);
}
exit(0);
}
Figure C.14 Calldaemonizeand then obtain login name