Provided by: manpages-ru-dev_4.27.0-1_all bug

НАИМЕНОВАНИЕ

       pthread_setname_np, pthread_getname_np - изменяет/возвращает имя нити

БИБЛИОТЕКА

       Библиотека потоков POSIX (libpthread, -lpthread)

ОБЗОР

       #define _GNU_SOURCE             /* Смотрите feature_test_macros(7) */
       #include <pthread.h>

       int pthread_setname_np(pthread_t thread, const char *name);
       int pthread_getname_np(pthread_t thread, char name[.size], size_t size);

ОПИСАНИЕ

       By   default,   all   the  threads  created  using  pthread_create()   inherit  the  program  name.   The
       pthread_setname_np()  function can be used to set a unique name for a thread, which  can  be  useful  for
       debugging multithreaded applications.  The thread name is a meaningful C language string, whose length is
       restricted  to  16 characters, including the terminating null byte ('\0').  The thread argument specifies
       the thread whose name is to be changed; name specifies the new name.

       The pthread_getname_np()  function can be used to retrieve the name of the thread.  The  thread  argument
       specifies  the  thread whose name is to be retrieved.  The buffer name is used to return the thread name;
       size specifies the number of bytes available in name.  The buffer specified by name should be at least 16
       characters in length.  The returned thread name in the output buffer will be null terminated.

ВОЗВРАЩАЕМОЕ ЗНАЧЕНИЕ

       При успешном выполнении эти функции возвращают 0; при ошибке возвращается ненулевой номер ошибки.

ОШИБКИ

       Функция pthread_setname_np() может завершиться со следующей ошибкой:

       ERANGE Длина строки, на которую ссылается name, превышает разрешённую.

       Функция pthread_getname_np() может завершиться со следующей ошибкой:

       ERANGE The buffer specified by name and size is too small to hold the thread name.

       If either of these functions fails to open /proc/self/task/tid/comm, then the call may fail with  one  of
       the errors described in open(2).

АТРИБУТЫ

       Описание терминов данного раздела смотрите в attributes(7).
       ┌─────────────────────────────────────────────────────────────────────┬──────────────────────┬──────────┐
       │ ИнтерфейсАтрибутЗначение │
       ├─────────────────────────────────────────────────────────────────────┼──────────────────────┼──────────┤
       │ pthread_setname_np(), pthread_getname_np()                          │ Безвредность в нитях │ MT-Safe  │
       └─────────────────────────────────────────────────────────────────────┴──────────────────────┴──────────┘

СТАНДАРТЫ

       GNU, о чём свидетельствует наличие суффикса «_np» (nonportable) в именах.

ИСТОРИЯ

       glibc 2.12.

ПРИМЕЧАНИЯ

       pthread_setname_np()   internally  writes  to  the  thread-specific comm file under the /proc filesystem:
       /proc/self/task/tid/comm.  pthread_getname_np()  retrieves it from the same location.

ПРИМЕРЫ

       Представленная ниже программа показывает использование pthread_setname_np() и pthread_getname_np().

       Пример сеанса работы с программой:

           $ ./a.out
           Created a thread. Default name is: a.out
           The thread name after setting it is THREADFOO.
           ^Z                           # Suspend the program
           [1]+  Stopped           ./a.out
           $ ps H -C a.out -o 'pid tid cmd comm'
             PID   TID CMD                         COMMAND
            5990  5990 ./a.out                     a.out
            5990  5991 ./a.out                     THREADFOO
           $ cat /proc/5990/task/5990/comm
           a.out
           $ cat /proc/5990/task/5991/comm
           THREADFOO

   Исходный код программы

       #define _GNU_SOURCE
       #include <err.h>
       #include <errno.h>
       #include <pthread.h>
       #include <stdio.h>
       #include <stdlib.h>
       #include <string.h>
       #include <unistd.h>

       #define NAMELEN 16

       static void *
       threadfunc(void *parm)
       {
           sleep(5);          // allow main program to set the thread name
           return NULL;
       }

       int
       main(int argc, char *argv[])
       {
           pthread_t thread;
           int rc;
           char thread_name[NAMELEN];

           rc = pthread_create(&thread, NULL, threadfunc, NULL);
           if (rc != 0)
               errc(EXIT_FAILURE, rc, "pthread_create");

           rc = pthread_getname_np(thread, thread_name, NAMELEN);
           if (rc != 0)
               errc(EXIT_FAILURE, rc, "pthread_getname_np");

           printf("Created a thread. Default name is: %s\n", thread_name);
           rc = pthread_setname_np(thread, (argc > 1) ? argv[1] : "THREADFOO");
           if (rc != 0)
               errc(EXIT_FAILURE, rc, "pthread_setname_np");

           sleep(2);

           rc = pthread_getname_np(thread, thread_name, NAMELEN);
           if (rc != 0)
               errc(EXIT_FAILURE, rc, "pthread_getname_np");
           printf("The thread name after setting it is %s.\n", thread_name);

           rc = pthread_join(thread, NULL);
           if (rc != 0)
               errc(EXIT_FAILURE, rc, "pthread_join");

           printf("Done\n");
           exit(EXIT_SUCCESS);
       }

СМОТРИТЕ ТАКЖЕ

       prctl(2), pthread_create(3), pthreads(7)

ПЕРЕВОД

       Русский перевод этой страницы руководства разработал(и) Alexey, Azamat Hackimov
       <azamat.hackimov@gmail.com>, kogamatranslator49 <r.podarov@yandex.ru>, Darima Kogan
       <silverdk99@gmail.com>, Max Is <ismax799@gmail.com>, Yuri Kozlov <yuray@komyakino.ru>, Иван Павлов
       <pavia00@gmail.com> и Kirill Rekhov <krekhov.dev@gmail.com>

       Этот перевод является свободной программной документацией; он распространяется на условиях общедоступной
       лицензии GNU (GNU General Public License - GPL, https://www.gnu.org/licenses/gpl-3.0.html версии 3 или
       более поздней) в отношении авторского права, но БЕЗ КАКИХ-ЛИБО ГАРАНТИЙ.

       Если вы обнаружите какие-либо ошибки в переводе этой страницы руководства, пожалуйста, сообщите об этом
       разработчику(ам) по его(их) адресу(ам) электронной почты или по адресу списка рассылки русских
       переводчиков.

Справочные страницы Linux 6.9.1                  15 июня 2024 г.                           pthread_setname_np(3)