whoami.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*!
  2. * \file lib/gis/whoami.c
  3. *
  4. * \brief GIS Library - Login name functions.
  5. *
  6. * (C) 2001-2009 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 Original author CERL
  12. */
  13. #include <unistd.h>
  14. #include <stdlib.h>
  15. #ifndef __MINGW32__
  16. #include <pwd.h>
  17. #endif
  18. #include <grass/gis.h>
  19. /*!
  20. * \brief Gets user's name.
  21. *
  22. * Returns a pointer to a string containing the user's login name.
  23. *
  24. * Tries getlogin() first, then goes to the password file.
  25. * However, some masscomp getlogin() fails in ucb universe
  26. * because the ttyname(0) rotuine fails in ucb universe.
  27. * So we check for this, too.
  28. *
  29. * \return pointer to string ("anonymous" by default)
  30. */
  31. const char *G_whoami(void)
  32. {
  33. static int initialized;
  34. static const char *name;
  35. if (G_is_initialized(&initialized))
  36. return name;
  37. #ifdef __MINGW32__
  38. name = getenv("USERNAME");
  39. #endif
  40. if (!name || !*name)
  41. name = getenv("LOGNAME");
  42. if (!name || !*name)
  43. name = getenv("USER");
  44. #ifndef __MINGW32__
  45. if (!name || !*name) {
  46. struct passwd *p = getpwuid(getuid());
  47. if (p && p->pw_name && *p->pw_name)
  48. name = G_store(p->pw_name);
  49. }
  50. #endif
  51. if (!name || !*name)
  52. name = "anonymous";
  53. G_initialize_done(&initialized);
  54. return name;
  55. }