pthread_getname.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /* pthread_getname_np -- Get thread name. Linux version
  2. Copyright (C) 2010-2016 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public License as
  6. published by the Free Software Foundation; either version 2.1 of the
  7. License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; see the file COPYING.LIB. If
  14. not, see <http://www.gnu.org/licenses/>. */
  15. #include <errno.h>
  16. #include <fcntl.h>
  17. #include <pthreadP.h>
  18. #include <stdio.h>
  19. #include <string.h>
  20. #include <unistd.h>
  21. #include <sys/prctl.h>
  22. #include <not-cancel.h>
  23. int
  24. pthread_getname_np (pthread_t th, char *buf, size_t len)
  25. {
  26. const struct pthread *pd = (const struct pthread *) th;
  27. /* Unfortunately the kernel headers do not export the TASK_COMM_LEN
  28. macro. So we have to define it here. */
  29. #define TASK_COMM_LEN 16
  30. if (len < TASK_COMM_LEN)
  31. return ERANGE;
  32. if (pd == THREAD_SELF)
  33. return prctl (PR_GET_NAME, buf) ? errno : 0;
  34. #define FMT "/proc/self/task/%u/comm"
  35. char fname[sizeof (FMT) + 8];
  36. sprintf (fname, FMT, (unsigned int) pd->tid);
  37. int fd = open_not_cancel_2 (fname, O_RDONLY);
  38. if (fd == -1)
  39. return errno;
  40. int res = 0;
  41. ssize_t n = TEMP_FAILURE_RETRY (read_not_cancel (fd, buf, len));
  42. if (n < 0)
  43. res = errno;
  44. else
  45. {
  46. if (buf[n - 1] == '\n')
  47. buf[n - 1] = '\0';
  48. else if (n == len)
  49. res = ERANGE;
  50. else
  51. buf[n] = '\0';
  52. }
  53. close_not_cancel_no_status (fd);
  54. return res;
  55. }