pthread_setname.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* pthread_setname_np -- Set 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_setname_np (pthread_t th, const char *name)
  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. size_t name_len = strlen (name);
  31. if (name_len >= TASK_COMM_LEN)
  32. return ERANGE;
  33. if (pd == THREAD_SELF)
  34. return prctl (PR_SET_NAME, name) ? errno : 0;
  35. #define FMT "/proc/self/task/%u/comm"
  36. char fname[sizeof (FMT) + 8];
  37. sprintf (fname, FMT, (unsigned int) pd->tid);
  38. int fd = open_not_cancel_2 (fname, O_RDWR);
  39. if (fd == -1)
  40. return errno;
  41. int res = 0;
  42. ssize_t n = TEMP_FAILURE_RETRY (write_not_cancel (fd, name, name_len));
  43. if (n < 0)
  44. res = errno;
  45. else if (n != name_len)
  46. res = EIO;
  47. close_not_cancel_no_status (fd);
  48. return res;
  49. }