Figure C.13 shows a solution. The results depend on the platform. Recall that daemonize closes all open file descriptors and then reopens the first three to /dev/null. This means that the process won't have a controlling terminal, so getlogin won't be able to look in the utmp file for the process's login entry. Thus, on Linux 2.4.22 and Solaris 9, we find that a daemon has no login name.
Figure C.13. Call daemonize and then obtain login name
#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);
}
Under FreeBSD 5.2.1 and Mac OS X 10.3, however, the login name is maintained in the process table and copied across a fork. This means that the process can always get the login name, unless the parent didn't have one to start out (such as init when the system is bootstrapped).
|