getlogin.c 667 B

12345678910111213141516171819202122232425262728293031323334353637
  1. #include <unistd.h>
  2. #include <pwd.h>
  3. #include <string.h>
  4. #include <errno.h>
  5. #include <sys/stat.h>
  6. static char _name[64]; /* NAME_MAX ? */
  7. char * getlogin(void) {
  8. int tty = STDIN_FILENO;
  9. if (!isatty(tty)) {
  10. tty = STDOUT_FILENO;
  11. if (!isatty(tty)) {
  12. tty = STDERR_FILENO;
  13. if (!isatty(tty)) {
  14. errno = ENOTTY;
  15. return NULL;
  16. }
  17. }
  18. }
  19. char * name = ttyname(tty);
  20. if (!name) return NULL;
  21. /* Get the owner */
  22. struct stat statbuf;
  23. stat(name, &statbuf);
  24. struct passwd * passwd = getpwuid(statbuf.st_uid);
  25. if (!passwd) return NULL;
  26. if (!passwd->pw_name) return NULL;
  27. memcpy(_name, passwd->pw_name, strlen(passwd->pw_name));
  28. return _name;
  29. }