Книга: Programming with POSIX® Threads

6.5.1 User and terminal identification

6.5.1 User and terminal identification

int getlogin_r (char *name, size_t namesize);

char *ctermid (char *s);

int ttyname_r (int fildes, char *name, size_t namesize);

These functions return data to a caller-specified buffer. For getlogin_r, namesize must be at least LOGIN_NAME_MAX characters. For ttyname_r, namesize must be at least TTY_NAME_MAX characters. Either function returns a value of 0 on success, or an error number on failure. In addition to errors that might be returned by getlogin or ttyname, getlogin_r and ttyname_r may return ERANGE to indicate that the name buffer is too small.

Pthreads requires that when ctermid (which has not changed) is used in a threaded environment, the s return argument must be specified as a pointer to a character buffer having at least L_ctermid bytes. It was felt that this restriction was sufficient, without defining a new variant to also specify the size of the buffer. Program getlogin.c shows how to call these functions. Notice that these functions do not depend on threads, or <pthread.h>, in any way, and may even be provided on systems that don't support threads.

? getlogin.c

1 #include <limits.h>
2 #include "errors.h"

3
4 /*
5 * If either TTY_NAME_MAX or LOGIN_NAME_MAX are undefined
6 * (this means they are "indeterminate" values), assume a
7 * reasonable size (for simplicity) rather than using sysconf
8 * and dynamically allocating the buffers.
9 */
10 #ifndef TTY_NAME_MAX
11 # define TTY_NAME_MAX 128
12 #endif
13 #ifndef LOGIN_NAME_MAX
14 # define LOGIN_NAME_MAX 32
15 #endif

16
17 int main (int argc, char *argv[])
18 {
19 char login_str[LOGIN_NAME_MAX];
20 char stdin_str[TTY_NAME_MAX];
21 char cterm_str[L_ctermid], *cterm_str_ptr;
22 int status;

23
24 status = getlogin_r (login_str, sizeof (login_str));
25 if (status != 0)
26 err_abort (status, "Get login");
27 cterm_str_ptr = ctermid (cterm_str);
28 if (cterm_str_ptr == NULL)
29 errno_abort ("Get cterm");
30 status = ttyname_r (0, stdin_str, sizeof (stdin_str));
31 if (status != 0)
32 err_abort (status, "Get stdin");
33 printf ("User: %s, cterm: %s, fd 0: %sn",
34 login_str, cterm_str, stdin_str);
35 return 0;

Оглавление книги


Генерация: 1.291. Запросов К БД/Cache: 3 / 1
поделиться
Вверх Вниз