getusershell.c 565 B

1234567891011121314151617181920212223242526272829303132
  1. #define _GNU_SOURCE
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. static const char defshells[] = "/bin/sh\n/bin/csh\n";
  5. static char *line;
  6. static size_t linesize;
  7. static FILE *f;
  8. void endusershell(void)
  9. {
  10. if (f) fclose(f);
  11. f = 0;
  12. }
  13. void setusershell(void)
  14. {
  15. if (!f) f = fopen("/etc/shells", "rbe");
  16. if (!f) f = fmemopen((void *)defshells, sizeof defshells - 1, "rb");
  17. }
  18. char *getusershell(void)
  19. {
  20. ssize_t l;
  21. if (!f) setusershell();
  22. if (!f) return 0;
  23. l = getline(&line, &linesize, f);
  24. if (l <= 0) return 0;
  25. if (line[l-1]=='\n') line[l-1]=0;
  26. return line;
  27. }