whoami.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /**
  2. * \file whoami.c
  3. *
  4. * \brief GIS Library - Login name functions.
  5. *
  6. * (C) 2001-2008 by the GRASS Development Team
  7. *
  8. * This program is free software under the GNU General Public License
  9. * (>=v2). Read the file COPYING that comes with GRASS for details.
  10. *
  11. * \author GRASS GIS Development Team
  12. *
  13. * \date 1999-2008
  14. */
  15. #include <unistd.h>
  16. #include <stdlib.h>
  17. #ifndef __MINGW32__
  18. #include <pwd.h>
  19. #endif
  20. #include <grass/gis.h>
  21. /**
  22. * \brief Gets user's name.
  23. *
  24. * Returns a pointer to a string containing the user's login name.
  25. *
  26. * Tries getlogin() first, then goes to the password file.
  27. * However, some masscomp getlogin() fails in ucb universe
  28. * because the ttyname(0) rotuine fails in ucb universe.
  29. * So we check for this, too.
  30. *
  31. * \retval char * Pointer to string
  32. */
  33. const char *G_whoami(void)
  34. {
  35. static int initialized;
  36. static const char *name;
  37. if (G_is_initialized(&initialized))
  38. return name;
  39. #ifdef __MINGW32__
  40. name = getenv("USERNAME");
  41. #endif
  42. if (!name || !*name)
  43. name = getenv("LOGNAME");
  44. if (!name || !*name)
  45. name = getenv("USER");
  46. #ifndef __MINGW32__
  47. if (!name || !*name) {
  48. struct passwd *p = getpwuid(getuid());
  49. if (p && p->pw_name && *p->pw_name)
  50. name = G_store(p->pw_name);
  51. }
  52. #endif
  53. if (!name || !*name)
  54. name = "anonymous";
  55. G_initialize_done(&initialized);
  56. return name;
  57. }