Debian Codegraph @

upstream/mageia-cauldron/man1/perlclib.1

raw
1 .\" -*- mode: troff; coding: utf-8 -*-
2 .\" Automatically generated by Pod::Man v6.0.2 (Pod::Simple 3.45)
3 .\"
4 .\" Standard preamble:
5 .\" ========================================================================
6 .de Sp \" Vertical space (when we can't use .PP)
7 .if t .sp .5v
8 .if n .sp
9 ..
10 .de Vb \" Begin verbatim text
11 .ft CW
12 .nf
13 .ne \\$1
14 ..
15 .de Ve \" End verbatim text
16 .ft R
17 .fi
18 ..
19 .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>.
20 .ie n \{\
21 . ds C` ""
22 . ds C' ""
23 'br\}
24 .el\{\
25 . ds C`
26 . ds C'
27 'br\}
28 .\"
29 .\" Escape single quotes in literal strings from groff's Unicode transform.
30 .ie \n(.g .ds Aq \(aq
31 .el .ds Aq '
32 .\"
33 .\" If the F register is >0, we'll generate index entries on stderr for
34 .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
35 .\" entries marked with X<> in POD. Of course, you'll have to process the
36 .\" output yourself in some meaningful fashion.
37 .\"
38 .\" Avoid warning from groff about undefined register 'F'.
39 .de IX
40 ..
41 .nr rF 0
42 .if \n(.g .if rF .nr rF 1
43 .if (\n(rF:(\n(.g==0)) \{\
44 . if \nF \{\
45 . de IX
46 . tm Index:\\$1\t\\n%\t"\\$2"
47 ..
48 . if !\nF==2 \{\
49 . nr % 0
50 . nr F 2
51 . \}
52 . \}
53 .\}
54 .rr rF
55 .\"
56 .\" Required to disable full justification in groff 1.23.0.
57 .if n .ds AD l
58 .\" ========================================================================
59 .\"
60 .IX Title "PERLCLIB 1"
61 .TH PERLCLIB 1 2025-06-24 "perl v5.42.0" "Perl Programmers Reference Guide"
62 .\" For nroff, turn off justification. Always turn off hyphenation; it makes
63 .\" way too many mistakes in technical documents.
64 .if n .ad l
65 .nh
66 .SH NAME
67 perlclib \- Interacting with standard C library functions
68 .SH DESCRIPTION
69 .IX Header "DESCRIPTION"
70 The perl interpreter is written in C; XS code also expands to C.
71 Inevitably, this code will call some functions from the C library,
72 \&\f(CW\*(C`libc\*(C'\fR. This document gives some guidance on interfacing with that
73 library.
74 .PP
75 One thing Perl porters should note is that \fIperl\fR doesn\*(Aqt tend to use that
76 much of the C standard library internally; you\*(Aqll see very little use of,
77 for example, the \fIctype.h\fR functions in there. This is because Perl
78 tends to reimplement or abstract standard library functions, so that we
79 know exactly how they\*(Aqre going to operate.
80 .SH "libc functions to avoid"
81 .IX Header "libc functions to avoid"
82 There are many many libc functions. Most of them are fair game to use,
83 but some are not. Some of the possible reasons are:
84 .IP \(bu 4
85 They likely will interfere with the perl interpreter\*(Aqs functioning,
86 such as its bookkeeping, or signal handling, or memory allocation,
87 or any number of harmful things.
88 .IP \(bu 4
89 They aren\*(Aqt implemented on all platforms, but there is an alternative
90 that is.
91 .Sp
92 Or they may be buggy or deprecated on some or all platforms.
93 .IP \(bu 4
94 They aren\*(Aqt suitable for multi\-threaded operation, but there is an
95 alternative that is, and is just as easily usable.
96 .Sp
97 You may not expect your code to ever be used under threads, but code has
98 a way of being adapted beyond our initial expectations. If it is just
99 as easy to use something that can be used under threads, it\*(Aqs better to
100 use that now, just in case.
101 .IP \(bu 4
102 In functions that deal with strings, complications may arise because the
103 string may be encoded in different ways, for example in UTF\-8. For
104 these, it is likely better to place the string in a SV and use the Perl
105 SV string handling functions that contain extensive logic to deal with
106 this.
107 .IP \(bu 4
108 In functions that deal with numbers, complications may arise because the
109 numbers get too big or small, and what those limits are depends on the
110 current platform. Again, the Perl SV numeric data types have extensive
111 logic to take care of these kinds of issues.
112 .IP \(bu 4
113 They are locale\-aware, and your caller may not want this.
114 .PP
115 The following commentary and tables give some functions in the first
116 column that shouldn\*(Aqt be used in C or XS code, with the preferred
117 alternative (if any) in the second column.
118 .SS Conventions
119 .IX Subsection "Conventions"
120 In the following tables:
121 .ie n .IP """~""" 3
122 .el .IP \f(CW~\fR 3
123 .IX Item "~"
124 marks the function as deprecated; it should not be used regardless.
125 .ie n .IP """t""" 3
126 .el .IP \f(CWt\fR 3
127 .IX Item "t"
128 is a type.
129 .ie n .IP """p""" 3
130 .el .IP \f(CWp\fR 3
131 .IX Item "p"
132 is a pointer.
133 .ie n .IP """n""" 3
134 .el .IP \f(CWn\fR 3
135 .IX Item "n"
136 is a number.
137 .ie n .IP """s""" 3
138 .el .IP \f(CWs\fR 3
139 .IX Item "s"
140 is a string.
141 .PP
142 \&\f(CW\*(C`sv\*(C'\fR, \f(CW\*(C`av\*(C'\fR, \f(CW\*(C`hv\*(C'\fR, etc. represent variables of their respective types.
143 .SS "File Operations"
144 .IX Subsection "File Operations"
145 Instead of the \fIstdio.h\fR functions, you should use the Perl abstraction
146 layer. Instead of \f(CW\*(C`FILE*\*(C'\fR types, you need to be handling \f(CW\*(C`PerlIO*\*(C'\fR
147 types. Don\*(Aqt forget that with the new PerlIO layered I/O abstraction
148 \&\f(CW\*(C`FILE*\*(C'\fR types may not even be available. See also the \f(CW\*(C`perlapio\*(C'\fR
149 documentation for more information about the following functions:
150 .PP
151 .Vb 1
152 \& Instead Of: Use:
153 \&
154 \& stdin PerlIO_stdin()
155 \& stdout PerlIO_stdout()
156 \& stderr PerlIO_stderr()
157 \&
158 \& fopen(fn, mode) PerlIO_open(fn, mode)
159 \& freopen(fn, mode, stream) PerlIO_reopen(fn, mode, perlio) (Dep\-
160 \& recated)
161 \& fflush(stream) PerlIO_flush(perlio)
162 \& fclose(stream) PerlIO_close(perlio)
163 .Ve
164 .SS "File Input and Output"
165 .IX Subsection "File Input and Output"
166 .Vb 1
167 \& Instead Of: Use:
168 \&
169 \& fprintf(stream, fmt, ...) PerlIO_printf(perlio, fmt, ...)
170 \&
171 \& [f]getc(stream) PerlIO_getc(perlio)
172 \& [f]putc(stream, n) PerlIO_putc(perlio, n)
173 \& ungetc(n, stream) PerlIO_ungetc(perlio, n)
174 .Ve
175 .PP
176 Note that the PerlIO equivalents of \f(CW\*(C`fread\*(C'\fR and \f(CW\*(C`fwrite\*(C'\fR are slightly
177 different from their C library counterparts:
178 .PP
179 .Vb 2
180 \& fread(p, size, n, stream) PerlIO_read(perlio, buf, numbytes)
181 \& fwrite(p, size, n, stream) PerlIO_write(perlio, buf, numbytes)
182 \&
183 \& fputs(s, stream) PerlIO_puts(perlio, s)
184 .Ve
185 .PP
186 There is no equivalent to \f(CW\*(C`fgets\*(C'\fR (or the deprecated \f(CW\*(C`gets\*(C'\fR); one
187 should use \f(CW\*(C`sv_gets\*(C'\fR instead:
188 .PP
189 .Vb 1
190 \& fgets(s, n, stream) sv_gets(sv, perlio, append)
191 .Ve
192 .SS "File Positioning"
193 .IX Subsection "File Positioning"
194 .Vb 1
195 \& Instead Of: Use:
196 \&
197 \& feof(stream) PerlIO_eof(perlio)
198 \& fseek(stream, n, whence) PerlIO_seek(perlio, n, whence)
199 \& rewind(stream) PerlIO_rewind(perlio)
200 \&
201 \& fgetpos(stream, p) PerlIO_getpos(perlio, sv)
202 \& fsetpos(stream, p) PerlIO_setpos(perlio, sv)
203 \&
204 \& ferror(stream) PerlIO_error(perlio)
205 \& clearerr(stream) PerlIO_clearerr(perlio)
206 .Ve
207 .SS "Memory Management and String Handling"
208 .IX Subsection "Memory Management and String Handling"
209 .Vb 1
210 \& Instead Of: Use:
211 \&
212 \& t* p = malloc(n) Newx(p, n, t)
213 \& t* p = calloc(n, s) Newxz(p, n, t)
214 \& p = realloc(p, n) Renew(p, n, t)
215 .Ve
216 .PP
217 It is not portable to try to allocate 0 bytes; allocating 1 or more is
218 portable. Never pass pointers between \f(CW\*(C`Newx\*(C'\fR, \f(CW\*(C`Renew\*(C'\fR, \f(CW\*(C`Safefree\*(C'\fR and
219 \&\fIlibc\fR equivalents \f(CW\*(C`malloc\*(C'\fR, \f(CW\*(C`realloc\*(C'\fR, \f(CW\*(C`free\*(C'\fR. They are not from the
220 same memory pool or allocator. Either an instant or delayed \fISEGV\fR will
221 occur, or subtle memory leaks or subtle heap corruption.
222 .PP
223 .Vb 3
224 \& memcpy(dst, src, n) Copy(src, dst, n, t)
225 \& memmove(dst, src, n) Move(src, dst, n, t)
226 \& memcpy(dst, src, sizeof(t)) StructCopy(src, dst, t)
227 .Ve
228 .PP
229 Notice the different order of arguments to \f(CW\*(C`Copy\*(C'\fR and \f(CW\*(C`Move\*(C'\fR than used
230 in \f(CW\*(C`memcpy\*(C'\fR and \f(CW\*(C`memmove\*(C'\fR.
231 .PP
232 .Vb 3
233 \& memset(dst, 0, n * sizeof(t)) Zero(dst, n, t)
234 \& memzero(dst, 0) Zero(dst, n, char)
235 \& free(p) Safefree(p)
236 \&
237 \& strdup(p) savepv(p)
238 \& strndup(p, n) savepvn(p, n) (Hey, strndup doesn\*(Aqt
239 \& exist!)
240 .Ve
241 .PP
242 Sometimes instead of zeroing the allocated heap by using \fBNewxz()\fR you
243 should consider "poisoning" the data. This means writing a bit
244 pattern into it that should be illegal as pointers (and floating point
245 numbers), and also hopefully surprising enough as integers, so that
246 any code attempting to use the data without forethought will break
247 sooner rather than later. Poisoning can be done using the \fBPoison()\fR
248 macros, which have similar arguments to \fBZero()\fR:
249 .PP
250 .Vb 4
251 \& PoisonWith(dst, n, t, b) scribble memory with byte b
252 \& PoisonNew(dst, n, t) equal to PoisonWith(dst, n, t, 0xAB)
253 \& PoisonFree(dst, n, t) equal to PoisonWith(dst, n, t, 0xEF)
254 \& Poison(dst, n, t) equal to PoisonFree(dst, n, t)
255 \&
256 \& strstr(big, little) instr(big, little)
257 \& memmem(big, blen, little, len) ninstr(big, bigend, little, little_end)
258 \& strcmp(s1, s2) strLE(s1, s2) / strEQ(s1, s2)
259 \& / strGT(s1,s2)
260 \& strncmp(s1, s2, n) strnNE(s1, s2, n) / strnEQ(s1, s2, n)
261 \&
262 \& memcmp(p1, p2, n) memNE(p1, p2, n)
263 \& !memcmp(p1, p2, n) memEQ(p1, p2, n)
264 .Ve
265 .PP
266 Most of the time, though, you\*(Aqll want to be dealing with SVs internally
267 instead of raw \f(CW\*(C`char *\*(C'\fR strings:
268 .PP
269 .Vb 5
270 \& strlen(s) sv_len(sv)
271 \& strcpy(dt, src) sv_setpv(sv, s)
272 \& strncpy(dt, src, n) sv_setpvn(sv, s, n)
273 \& strcat(dt, src) sv_catpv(sv, s)
274 \& strncat(dt, src) sv_catpvn(sv, s)
275 .Ve
276 .PP
277 If you do need raw strings, use these instead:
278 .PP
279 .Vb 3
280 \& my_strnlen(s, maxlen)
281 \& my_strlcpy(dt, src, sizeof(dt))
282 \& my_strlcat(dt, src, sizeof(dt))
283 .Ve
284 .PP
285 Similiarly, you can use SVs for creating strings from formats
286 .PP
287 .Vb 2
288 \& sprintf(s, fmt, ...) sv_setpvf(sv, fmt, ...)
289 \& vsprintf(str, fmt, va_list) sv_vsetpvf(sv, fmt, va_list)
290 .Ve
291 .PP
292 Or for raw strings,
293 .PP
294 .Vb 3
295 \& my_snprintf(dt, len, fmt, ...)
296 \& my_vsnprintf(dt, len, fmt, va_list)
297 \& vsprintf(str, fmt, va_list) sv_vsnprintf(sv, fmt, va_list)
298 .Ve
299 .PP
300 Note also the existence of \f(CW\*(C`sv_catpvf\*(C'\fR and \f(CW\*(C`sv_vcatpvfn\*(C'\fR, combining
301 concatenation with formatting; and \f(CW\*(C`Perl_form\*(C'\fR() for
302 another form of formatted populating.
303 .PP
304 Note that glibc \f(CWprintf()\fR, \f(CWsprintf()\fR, etc. are buggy before glibc
305 version 2.17. They won\*(Aqt allow a \f(CW\*(C`%.s\*(C'\fR format with a precision to
306 create a string that isn\*(Aqt valid UTF\-8 if the current underlying locale
307 of the program is UTF\-8. What happens is that the \f(CW%s\fR and its
308 operand are simply skipped without any notice.
309 <https://sourceware.org/bugzilla/show_bug.cgi?id=6530>.
310 .SS "Character Class Tests"
311 .IX Subsection "Character Class Tests"
312 There are several types of character class tests that Perl implements.
313 All are more fully described in "Character classification" in perlapi and
314 "Character case changing" in perlapi.
315 .PP
316 The C library routines listed in the table below return values based on
317 the current locale. Use the entries in the final column for that
318 functionality. The other two columns always assume a POSIX (or C)
319 locale. The entries in the ASCII column are only meaningful for ASCII
320 inputs, returning FALSE for anything else. Use these only when you
321 \&\fBknow\fR that is what you want. The entries in the Latin1 column assume
322 that the non\-ASCII 8\-bit characters are as Unicode defines them, the
323 same as ISO\-8859\-1, often called Latin 1.
324 .PP
325 .Vb 1
326 \& Instead Of: Use for ASCII: Use for Latin1: Use for locale:
327 \&
328 \& isalnum(c) isALPHANUMERIC(c) isALPHANUMERIC_L1(c) isALPHANUMERIC_LC(c)
329 \& isalpha(c) isALPHA(c) isALPHA_L1(c) isALPHA_LC(u )
330 \& isascii(c) isASCII(c) isASCII_LC(c)
331 \& isblank(c) isBLANK(c) isBLANK_L1(c) isBLANK_LC(c)
332 \& iscntrl(c) isCNTRL(c) isCNTRL_L1(c) isCNTRL_LC(c)
333 \& isdigit(c) isDIGIT(c) isDIGIT_L1(c) isDIGIT_LC(c)
334 \& isgraph(c) isGRAPH(c) isGRAPH_L1(c) isGRAPH_LC(c)
335 \& islower(c) isLOWER(c) isLOWER_L1(c) isLOWER_LC(c)
336 \& isprint(c) isPRINT(c) isPRINT_L1(c) isPRINT_LC(c)
337 \& ispunct(c) isPUNCT(c) isPUNCT_L1(c) isPUNCT_LC(c)
338 \& isspace(c) isSPACE(c) isSPACE_L1(c) isSPACE_LC(c)
339 \& isupper(c) isUPPER(c) isUPPER_L1(c) isUPPER_LC(c)
340 \& isxdigit(c) isXDIGIT(c) isXDIGIT_L1(c) isXDIGIT_LC(c)
341 \&
342 \& tolower(c) toLOWER(c) toLOWER_L1(c)
343 \& toupper(c) toUPPER(c)
344 .Ve
345 .PP
346 For the corresponding functions like \f(CWiswupper()\fR, \fIetc.\fR, use
347 \&\f(CWisUPPER_uvchr()\fR for non\-locale; or \f(CWisUPPER_LC_uvchr()\fR for locale.
348 And use \f(CWtoLOWER_uvchr()\fR instead of \f(CWtowlower()\fR, \fIetc.\fR. There are
349 no direct equivalents for locale; best to put the string into an SV.
350 .PP
351 Don\*(Aqt use any of the functions like \f(CWisalnum_l()\fR. Those are
352 non\-portable, and interfere with Perl\*(Aqs internal handling.
353 .PP
354 To emphasize that you are operating only on ASCII characters, you can
355 append \f(CW\*(C`_A\*(C'\fR to each of the macros in the ASCII column: \f(CW\*(C`isALPHA_A\*(C'\fR,
356 \&\f(CW\*(C`isDIGIT_A\*(C'\fR, and so on.
357 .PP
358 (There is no entry in the Latin1 column for \f(CW\*(C`isascii\*(C'\fR even though there
359 is an \f(CW\*(C`isASCII_L1\*(C'\fR, which is identical to \f(CW\*(C`isASCII\*(C'\fR; the
360 latter name is clearer. There is no entry in the Latin1 column for
361 \&\f(CW\*(C`toupper\*(C'\fR because the result can be non\-Latin1. You have to use
362 \&\f(CW\*(C`toUPPER_uvchr\*(C'\fR, as described in "Character case changing" in perlapi.)
363 .PP
364 Note that the libc caseless comparisons are crippled; Unicode
365 provides a richer set, using the concept of folding. If you need
366 more than equality/non\-equality, it\*(Aqs probably best to store your
367 strings in an SV and use SV functions to do the comparision. Similarly
368 for collation.
369 .SS "\fIstdlib.h\fP functions"
370 .IX Subsection "stdlib.h functions"
371 .Vb 1
372 \& Instead Of: Use:
373 \&
374 \& atof(s) my_atof(s) or Atof(s)
375 \& atoi(s) grok_atoUV(s, &uv, &e)
376 \& atol(s) grok_atoUV(s, &uv, &e)
377 \& strtod(s, &p) Strtod(s, &p)
378 \& strtol(s, &p, n) Strtol(s, &p, b)
379 \& strtoul(s, &p, n) Strtoul(s, &p, b)
380 .Ve
381 .PP
382 But note that even the alternative functions are subject to locale; see
383 "Dealing with locales".
384 .PP
385 Typical use is to do range checks on \f(CW\*(C`uv\*(C'\fR before casting:
386 .PP
387 .Vb 9
388 \& int i; UV uv;
389 \& char* end_ptr = input_end;
390 \& if (grok_atoUV(input, &uv, &end_ptr)
391 \& && uv <= INT_MAX)
392 \& i = (int)uv;
393 \& ... /* continue parsing from end_ptr */
394 \& } else {
395 \& ... /* parse error: not a decimal integer in range 0 .. MAX_IV */
396 \& }
397 .Ve
398 .PP
399 Notice also the \f(CW\*(C`grok_bin\*(C'\fR, \f(CW\*(C`grok_hex\*(C'\fR, and \f(CW\*(C`grok_oct\*(C'\fR functions in
400 \&\fInumeric.c\fR for converting strings representing numbers in the respective
401 bases into \f(CW\*(C`NV\*(C'\fRs. Note that \fBgrok_atoUV()\fR doesn\*(Aqt handle negative inputs,
402 or leading whitespace (being purposefully strict).
403 .SS "Miscellaneous functions"
404 .IX Subsection "Miscellaneous functions"
405 You should not even \fBwant\fR to use \fIsetjmp.h\fR functions, but if you
406 think you do, use the \f(CW\*(C`JMPENV\*(C'\fR stack in \fIscope.h\fR instead.
407 .PP
408 .Vb 10
409 \& ~asctime() Perl_sv_strftime_tm()
410 \& ~asctime_r() Perl_sv_strftime_tm()
411 \& chsize() my_chsize()
412 \& ~ctime() Perl_sv_strftime_tm()
413 \& ~ctime_r() Perl_sv_strftime_tm()
414 \& ~cuserid() DO NOT USE; see its man page
415 \& dirfd() my_dirfd()
416 \& duplocale() Perl_setlocale()
417 \& ~ecvt() my_snprintf()
418 \& ~endgrent_r() endgrent()
419 \& ~endhostent_r() endhostent()
420 \& ~endnetent_r() endnetent()
421 \& ~endprotoent_r() endprotoent()
422 \& ~endpwent_r() endpwent()
423 \& ~endservent_r() endservent()
424 \& ~endutent() endutxent()
425 \& exit(n) my_exit(n)
426 \& ~fcvt() my_snprintf()
427 \& freelocale() Perl_setlocale()
428 \& ~ftw() nftw()
429 \& getenv(s) PerlEnv_getenv(s)
430 \& ~gethostbyaddr() getaddrinfo()
431 \& ~gethostbyname() getnameinfo()
432 \& ~getpass() DO NOT USE; see its man page
433 \& ~getpw() getpwuid()
434 \& ~getutent() getutxent()
435 \& ~getutid() getutxid()
436 \& ~getutline() getutxline()
437 \& ~gsignal() DO NOT USE; see its man page
438 \& localeconv() Perl_localeconv()
439 \& mblen() mbrlen()
440 \& mbtowc() mbrtowc()
441 \& newlocale() Perl_setlocale()
442 \& pclose() my_pclose()
443 \& popen() my_popen()
444 \& ~pututline() pututxline()
445 \& ~qecvt() my_snprintf()
446 \& ~qfcvt() my_snprintf()
447 \& querylocale() Perl_setlocale()
448 \& int rand() double Drand01()
449 \& srand(n) { seedDrand01((Rand_seed_t)n);
450 \& PL_srand_called = TRUE; }
451 \& ~readdir_r() readdir()
452 \& realloc() saferealloc(), Renew() or Renewc()
453 \& ~re_comp() regcomp()
454 \& ~re_exec() regexec()
455 \& ~rexec() rcmd()
456 \& ~rexec_af() rcmd()
457 \& setenv(s, val) my_setenv(s, val)
458 \& ~setgrent_r() setgrent()
459 \& ~sethostent_r() sethostent()
460 \& setlocale() Perl_setlocale()
461 \& setlocale_r() Perl_setlocale()
462 \& ~setnetent_r() setnetent()
463 \& ~setprotoent_r() setprotoent()
464 \& ~setpwent_r() setpwent()
465 \& ~setservent_r() setservent()
466 \& ~setutent() setutxent()
467 \& sigaction() rsignal(signo, handler)
468 \& ~siginterrupt() rsignal() with the SA_RESTART flag instead
469 \& signal(signo, handler) rsignal(signo, handler)
470 \& ~ssignal() DO NOT USE; see its man page
471 \& strcasecmp() a Perl foldEQ\-family function
472 \& strerror() sv_string_from_errnum()
473 \& strerror_l() sv_string_from_errnum()
474 \& strerror_r() sv_string_from_errnum()
475 \& strftime() Perl_sv_strftime_tm()
476 \& strtod() my_strtod() or Strtod()
477 \& system(s) Don\*(Aqt. Look at pp_system or use my_popen.
478 \& ~tempnam() mkstemp()
479 \& ~tmpnam() mkstemp()
480 \& tmpnam_r() mkstemp()
481 \& uselocale() Perl_setlocale()
482 \& vsnprintf() my_vsnprintf()
483 \& wctob() wcrtomb()
484 \& wctomb() wcrtomb()
485 \& wsetlocale() Perl_setlocale()
486 .Ve
487 .PP
488 The Perl\-furnished alternatives are documented in perlapi, which you
489 should peruse anyway to see what all is available to you.
490 .PP
491 The lists are incomplete. Think when using an unlisted function if it
492 seems likely to interfere with Perl.
493 .SH "Dealing with locales"
494 .IX Header "Dealing with locales"
495 Like it or not, your code will be executed in the context of a locale,
496 as are all C language programs. See perllocale. Most libc calls are
497 not affected by the locale, but a surprising number are:
498 .PP
499 .Vb 10
500 \& addmntent() getspent_r() sethostent()
501 \& alphasort() getspnam() sethostent_r()
502 \& asctime() getspnam_r() setnetent()
503 \& asctime_r() getwc() setnetent_r()
504 \& asprintf() getwchar() setnetgrent()
505 \& atof() glob() setprotoent()
506 \& atoi() gmtime() setprotoent_r()
507 \& atol() gmtime_r() setpwent()
508 \& atoll() grantpt() setpwent_r()
509 \& btowc() iconv_open() setrpcent()
510 \& catopen() inet_addr() setservent()
511 \& ctime() inet_aton() setservent_r()
512 \& ctime_r() inet_network() setspent()
513 \& cuserid() inet_ntoa() sgetspent_r()
514 \& daylight inet_ntop() shm_open()
515 \& dirname() inet_pton() shm_unlink()
516 \& dprintf() initgroups() snprintf()
517 \& endaliasent() innetgr() sprintf()
518 \& endgrent() iruserok() sscanf()
519 \& endgrent_r() iruserok_af() strcasecmp()
520 \& endhostent() isalnum() strcasestr()
521 \& endhostent_r() isalnum_l() strcoll()
522 \& endnetent() isalpha() strerror()
523 \& endnetent_r() isalpha_l() strerror_l()
524 \& endprotoent() isascii() strerror_r()
525 \& endprotoent_r() isascii_l() strfmon()
526 \& endpwent() isblank() strfmon_l()
527 \& endpwent_r() isblank_l() strfromd()
528 \& endrpcent() iscntrl() strfromf()
529 \& endservent() iscntrl_l() strfroml()
530 \& endservent_r() isdigit() strftime()
531 \& endspent() isdigit_l() strftime_l()
532 \& err() isgraph() strncasecmp()
533 \& error() isgraph_l() strptime()
534 \& error_at_line() islower() strsignal()
535 \& errx() islower_l() strtod()
536 \& fgetwc() isprint() strtof()
537 \& fgetwc_unlocked() isprint_l() strtoimax()
538 \& fgetws() ispunct() strtol()
539 \& fgetws_unlocked() ispunct_l() strtold()
540 \& fnmatch() isspace() strtoll()
541 \& forkpty() isspace_l() strtoq()
542 \& fprintf() isupper() strtoul()
543 \& fputwc() isupper_l() strtoull()
544 \& fputwc_unlocked() iswalnum() strtoumax()
545 \& fputws() iswalnum_l() strtouq()
546 \& fputws_unlocked() iswalpha() strverscmp()
547 \& fscanf() iswalpha_l() strxfrm()
548 \& fwprintf() iswblank() swprintf()
549 \& fwscanf() iswblank_l() swscanf()
550 \& getaddrinfo() iswcntrl() syslog()
551 \& getaliasbyname_r() iswcntrl_l() timegm()
552 \& getaliasent_r() iswdigit() timelocal()
553 \& getdate() iswdigit_l() timezone
554 \& getdate_r() iswgraph() tolower()
555 \& getfsent() iswgraph_l() tolower_l()
556 \& getfsfile() iswlower() toupper()
557 \& getfsspec() iswlower_l() toupper_l()
558 \& getgrent() iswprint() towctrans()
559 \& getgrent_r() iswprint_l() towlower()
560 \& getgrgid() iswpunct() towlower_l()
561 \& getgrgid_r() iswpunct_l() towupper()
562 \& getgrnam() iswspace() towupper_l()
563 \& getgrnam_r() iswspace_l() tzname
564 \& getgrouplist() iswupper() tzset()
565 \& gethostbyaddr() iswupper_l() ungetwc()
566 \& gethostbyaddr_r() iswxdigit() vasprintf()
567 \& gethostbyname() iswxdigit_l() vdprintf()
568 \& gethostbyname2() isxdigit() verr()
569 \& gethostbyname2_r() isxdigit_l() verrx()
570 \& gethostbyname_r() localeconv() versionsort()
571 \& gethostent() localtime() vfprintf()
572 \& gethostent_r() localtime_r() vfscanf()
573 \& gethostid() MB_CUR_MAX vfwprintf()
574 \& getlogin() mblen() vprintf()
575 \& getlogin_r() mbrlen() vscanf()
576 \& getmntent() mbrtowc() vsnprintf()
577 \& getmntent_r() mbsinit() vsprintf()
578 \& getnameinfo() mbsnrtowcs() vsscanf()
579 \& getnetbyaddr() mbsrtowcs() vswprintf()
580 \& getnetbyaddr_r() mbstowcs() vsyslog()
581 \& getnetbyname() mbtowc() vwarn()
582 \& getnetbyname_r() mktime() vwarnx()
583 \& getnetent() nan() vwprintf()
584 \& getnetent_r() nanf() warn()
585 \& getnetgrent() nanl() warnx()
586 \& getnetgrent_r() nl_langinfo() wcrtomb()
587 \& getprotobyname() openpty() wcscasecmp()
588 \& getprotobyname_r() printf() wcschr()
589 \& getprotobynumber() psiginfo() wcscoll()
590 \& getprotobynumber_r() psignal() wcsftime()
591 \& getprotoent() putpwent() wcsncasecmp()
592 \& getprotoent_r() putspent() wcsnrtombs()
593 \& getpw() putwc() wcsrchr()
594 \& getpwent() putwchar() wcsrtombs()
595 \& getpwent_r() regcomp() wcstod()
596 \& getpwnam() regexec() wcstof()
597 \& getpwnam_r() res_nclose() wcstoimax()
598 \& getpwuid() res_ninit() wcstold()
599 \& getpwuid_r() res_nquery() wcstombs()
600 \& getrpcbyname_r() res_nquerydomain() wcstoumax()
601 \& getrpcbynumber_r() res_nsearch() wcswidth()
602 \& getrpcent_r() res_nsend() wcsxfrm()
603 \& getrpcport() rpmatch() wctob()
604 \& getservbyname() ruserok() wctomb()
605 \& getservbyname_r() ruserok_af() wctrans()
606 \& getservbyport() scandir() wctype()
607 \& getservbyport_r() scanf() wcwidth()
608 \& getservent() setaliasent() wordexp()
609 \& getservent_r() setgrent() wprintf()
610 \& getspent() setgrent_r() wscanf()
611 .Ve
612 .PP
613 (The list doesn\*(Aqt include functions that manipulate the locale, such as
614 \&\f(CWsetlocale()\fR.)
615 .PP
616 If any of these functions are called directly or indirectly from your
617 code, you are affected by the current locale.
618 .PP
619 The first thing to know about this list is that there are better
620 alternatives to many of the functions, which it\*(Aqs highly likely that you
621 should be using instead. See "libc functions to avoid" above.
622 This includes using Perl IO perlapio.
623 .PP
624 The second thing to know is that Perl is documented to not pay attention
625 to the current locale except for code executed within the scope of a
626 \&\f(CW\*(C`use\ locale\*(C'\fR statement. If you violate that, you may be creating
627 bugs, depending on the application.
628 .PP
629 The next thing to know is that many of these functions depend only on
630 the locale in regards to numeric values. Your code is likely to have
631 been written expecting that the decimal point (radix) character is a dot
632 (U+002E: FULL STOP), and that strings of integer numbers are not
633 separated into groups (1,000,000 in an American locale means a million;
634 your code is likely not expecting the commas.) The good news is that
635 normally (as of Perl v5.22), your code will get called with the locale
636 set so those expectations are met. Explicit action has to be taken to
637 change this (described a little ways below). This is accomplished by
638 Perl not actually switching into a locale that doesn\*(Aqt conform to these
639 expectations, except when explicitly told to do so. The Perl
640 input/output and formatting routines do this switching for you
641 automatically, if appropriate, and then switch back. If, for some
642 reason, you need to do it yourself, the easiest way from C and XS code
643 is to use the macro "\f(CW\*(C`WITH_LC_NUMERIC_SET_TO_NEEDED\*(C'\fR" in perlapi. You
644 can wrap this macro around an entire block of code that you want to be
645 executed in the correct environment. The bottom line is that your code
646 is likely to work as expected in this regard without you having to take
647 any action.
648 .PP
649 This leaves the remaining functions. Your code will get called with all
650 but the numeric locale portions set to the underlying locale. Often,
651 the locale is of not much import to your code, and you also won\*(Aqt have
652 to take any action; things will just work out. But you should examine
653 the man pages of the ones you use to verify this. Often, Perl has
654 better ways of doing the same functionality. Consider using SVs and
655 their access routines rather than calling the low level functions that,
656 for example, find how many bytes are in a UTF\-8 encoded character.
657 .PP
658 You can determine if you have been called from within the scope of a
659 \&\f(CW\*(C`use\ locale\*(C'\fR by using the boolen macro "\f(CW\*(C`IN_LOCALE\*(C'\fR" in perlapi.
660 .PP
661 If you need to not be in the underlying locale, you can call
662 "\f(CW\*(C`Perl_setlocale\*(C'\fR" in perlapi to change it temporarily to the one you
663 need (likely the "C" locale), and then change it back before returning.
664 This can be \fBvery\fR problematic on threaded perls on some platforms. See
665 "Dealing with embedded perls and threads".
666 .PP
667 A problem with changing the locale of a single category is that mojibake
668 can arise on some platforms if the \f(CW\*(C`LC_CTYPE\*(C'\fR category and the changed one
669 are not the same. On the platforms that that isn\*(Aqt an issue, the
670 preprocessor directive \f(CW\*(C`LIBC_HANDLES_MISMATCHED_CTYPE\*(C'\fR will be defined.
671 Otherwise, you may have to change more than one category to correctly
672 accomplish your task. And, there will be many locale combinations where
673 the mojibake likely won\*(Aqt happen, so you won\*(Aqt be confronted with this
674 until the code gets executed in the field by someone who doesn\*(Aqt speak
675 your language very well.
676 .PP
677 Earlier we mentioned that explicit action is required to have your code
678 get called with the numeric portions of the locale not meeting the
679 typical expectations of having a dot for the radix character and no
680 punctuation separating groups of digits. That action is to call the
681 function "\f(CW\*(C`switch_to_global_locale\*(C'\fR" in perlapi.
682 .PP
683 \&\f(CWswitch_to_global_locale()\fR was written initially to cope with the
684 \&\f(CW\*(C`Tk\*(C'\fR library, but is general enough for other similar situations. \f(CW\*(C`Tk\*(C'\fR
685 changes the global locale to match its expectations (later versions of
686 it allow this to be turned off). This presents a conflict with Perl
687 thinking it also controls the locale. Calling this function tells Perl to
688 yield control. Calling "\f(CW\*(C`sync_locale\*(C'\fR" in perlapi tells Perl to take
689 control again, accepting whatever the locale has been changed to in the
690 interim. If your code is called during that interim, all portions of
691 the locale will be the raw underlying values. Should you need to
692 manipulate numbers, you are on your own with regard to the radix
693 character and grouping. If you find yourself in this situation, it is
694 generally best to make the interval between the calls to these two
695 functions as short as possible, and avoid calculations until after perl
696 has control again.
697 .PP
698 It is important for perl to know about all the possible locale
699 categories on the platform, even if they aren\*(Aqt apparently used in your
700 program. Perl knows all of the Linux ones. If your platform has
701 others, you can submit an issue at
702 <https://github.com/Perl/perl5/issues> for inclusion of it in the next
703 release. In the meantime, it is possible to edit the Perl source to
704 teach it about the category, and then recompile. Search for instances
705 of, say, \f(CW\*(C`LC_PAPER\*(C'\fR in the source, and use that as a template to add
706 the omitted one.
707 .PP
708 There are further complications under multi\-threaded operation. Keep on
709 reading.
710 .SH "Dealing with embedded perls and threads"
711 .IX Header "Dealing with embedded perls and threads"
712 It is possible to embed a Perl interpreter within a larger program. See
713 perlembed.
714 .PP
715 MULTIPLICITY is the way this is accomplished internally; it is described in
716 "How multiple interpreters and concurrency are supported" in perlguts.
717 Multiple Perl interpreters may be embedded.
718 .PP
719 It is also possible to compile perl to support threading. See
720 perlthrtut. Perl\*(Aqs implementation of threading requires
721 MULTIPLICITY, but not the other way around.
722 .PP
723 MULTIPLICITY without threading means that only one thing runs at a time,
724 so there are no concurrency issues, but each component or instance can
725 affect the global state, potentially interfering with the execution of
726 other instances. This can happen if one instance:
727 .IP \(bu 4
728 changes the current working directory
729 .IP \(bu 4
730 changes the process\*(Aqs environment
731 .IP \(bu 4
732 changes the global locale the process is operating under
733 .IP \(bu 4
734 writes to shared memory or to a shared file
735 .IP \(bu 4
736 uses a shared file descriptor (including a database iterator)
737 .IP \(bu 4
738 raises a signal that functions in other instances are sensitive to
739 .PP
740 If your code doesn\*(Aqt do any of these things, nor depends on any of their
741 values, then Congratulations!!, you don\*(Aqt have to worry about MULTIPLICITY
742 or threading. But wait, a surprising number of libc functions do
743 depend on data global to the process in some way that may not be
744 immediately obvious. For example, calling \f(CW\*(C`\fR\f(CBstrtok\fR\f(CW\|(3)\*(C'\fR changes the
745 global state of a process, and thus needs special attention.
746 .PP
747 The section 3 libc uses that we know about that have MULTIPLICITY and/or
748 multi\-thread issues are:
749 .PP
750 .Vb 10
751 \& addmntent() getrpcent_r() re_exec()
752 \& alphasort() getrpcport() regcomp()
753 \& asctime() getservbyname() regerror()
754 \& asctime_r() getservbyname_r() regexec()
755 \& asprintf() getservbyport() res_nclose()
756 \& atof() getservbyport_r() res_ninit()
757 \& atoi() getservent() res_nquery()
758 \& atol() getservent_r() res_nquerydomain()
759 \& atoll() getspent() res_nsearch()
760 \& basename() getspent_r() res_nsend()
761 \& btowc() getspnam() rexec()
762 \& catgets() getspnam_r() rexec_af()
763 \& catopen() getttyent() rpmatch()
764 \& clearenv() getttynam() ruserok()
765 \& clearerr_unlocked() getusershell() ruserok_af()
766 \& crypt() getutent() scandir()
767 \& crypt_gensalt() getutid() scanf()
768 \& crypt_r() getutline() secure_getenv()
769 \& ctermid() getutxent() seed48()
770 \& ctermid_r() getutxid() seed48_r()
771 \& ctime() getutxline() setaliasent()
772 \& ctime_r() getwc() setcontext()
773 \& cuserid() getwchar() setenv()
774 \& daylight getwchar_unlocked() setfsent()
775 \& dbm_clearerr() getwc_unlocked() setgrent()
776 \& dbm_close() glob() setgrent_r()
777 \& dbm_delete() gmtime() sethostent()
778 \& dbm_error() gmtime_r() sethostent_r()
779 \& dbm_fetch() grantpt() sethostid()
780 \& dbm_firstkey() hcreate() setkey()
781 \& dbm_nextkey() hcreate_r() setlocale()
782 \& dbm_open() hdestroy() setlocale_r()
783 \& dbm_store() hdestroy_r() setlogmask()
784 \& dirname() hsearch() setnetent()
785 \& dlerror() hsearch_r() setnetent_r()
786 \& dprintf() iconv() setnetgrent()
787 \& drand48() iconv_open() setprotoent()
788 \& drand48_r() inet_addr() setprotoent_r()
789 \& ecvt() inet_aton() setpwent()
790 \& encrypt() inet_network() setpwent_r()
791 \& endaliasent() inet_ntoa() setrpcent()
792 \& endfsent() inet_ntop() setservent()
793 \& endgrent() inet_pton() setservent_r()
794 \& endgrent_r() initgroups() setspent()
795 \& endhostent() initstate_r() setstate_r()
796 \& endhostent_r() innetgr() setttyent()
797 \& endnetent() iruserok() setusershell()
798 \& endnetent_r() iruserok_af() setutent()
799 \& endnetgrent() isalnum() setutxent()
800 \& endprotoent() isalnum_l() sgetspent()
801 \& endprotoent_r() isalpha() sgetspent_r()
802 \& endpwent() isalpha_l() shm_open()
803 \& endpwent_r() isascii() shm_unlink()
804 \& endrpcent() isascii_l() siginterrupt()
805 \& endservent() isblank() sleep()
806 \& endservent_r() isblank_l() snprintf()
807 \& endspent() iscntrl() sprintf()
808 \& endttyent() iscntrl_l() srand48()
809 \& endusershell() isdigit() srand48_r()
810 \& endutent() isdigit_l() srandom_r()
811 \& endutxent() isgraph() sscanf()
812 \& erand48() isgraph_l() ssignal()
813 \& erand48_r() islower() strcasecmp()
814 \& err() islower_l() strcasestr()
815 \& error() isprint() strcoll()
816 \& error_at_line() isprint_l() strerror()
817 \& errx() ispunct() strerror_l()
818 \& ether_aton() ispunct_l() strerror_r()
819 \& ether_ntoa() isspace() strfmon()
820 \& execlp() isspace_l() strfmon_l()
821 \& execvp() isupper() strfromd()
822 \& execvpe() isupper_l() strfromf()
823 \& exit() iswalnum() strfroml()
824 \& _\|_fbufsize() iswalnum_l() strftime()
825 \& fcloseall() iswalpha() strftime_l()
826 \& fcvt() iswalpha_l() strncasecmp()
827 \& fflush_unlocked() iswblank() strptime()
828 \& fgetc_unlocked() iswblank_l() strsignal()
829 \& fgetgrent() iswcntrl() strtod()
830 \& fgetpwent() iswcntrl_l() strtof()
831 \& fgetspent() iswdigit() strtoimax()
832 \& fgets_unlocked() iswdigit_l() strtok()
833 \& fgetwc() iswgraph() strtol()
834 \& fgetwc_unlocked() iswgraph_l() strtold()
835 \& fgetws() iswlower() strtoll()
836 \& fgetws_unlocked() iswlower_l() strtoq()
837 \& fnmatch() iswprint() strtoul()
838 \& forkpty() iswprint_l() strtoull()
839 \& _\|_fpending() iswpunct() strtoumax()
840 \& fprintf() iswpunct_l() strtouq()
841 \& _\|_fpurge() iswspace() strverscmp()
842 \& fputc_unlocked() iswspace_l() strxfrm()
843 \& fputs_unlocked() iswupper() swapcontext()
844 \& fputwc() iswupper_l() swprintf()
845 \& fputwc_unlocked() iswxdigit() swscanf()
846 \& fputws() iswxdigit_l() sysconf()
847 \& fputws_unlocked() isxdigit() syslog()
848 \& fread_unlocked() isxdigit_l() system()
849 \& fscanf() jrand48() tdelete()
850 \& _\|_fsetlocking() jrand48_r() tempnam()
851 \& fts_children() l64a() tfind()
852 \& fts_read() lcong48() timegm()
853 \& ftw() lcong48_r() timelocal()
854 \& fwprintf() lgamma() timezone
855 \& fwrite_unlocked() lgammaf() tmpnam()
856 \& fwscanf() lgammal() tmpnam_r()
857 \& gamma() localeconv() tolower()
858 \& gammaf() localtime() tolower_l()
859 \& gammal() localtime_r() toupper()
860 \& getaddrinfo() login() toupper_l()
861 \& getaliasbyname() login_tty() towctrans()
862 \& getaliasbyname_r() logout() towlower()
863 \& getaliasent() logwtmp() towlower_l()
864 \& getaliasent_r() lrand48() towupper()
865 \& getchar_unlocked() lrand48_r() towupper_l()
866 \& getcontext() makecontext() tsearch()
867 \& getc_unlocked() mallinfo() ttyname()
868 \& get_current_dir_name() MB_CUR_MAX ttyname_r()
869 \& getdate() mblen() ttyslot()
870 \& getdate_r() mbrlen() twalk()
871 \& getenv() mbrtowc() twalk_r()
872 \& getfsent() mbsinit() tzname
873 \& getfsfile() mbsnrtowcs() tzset()
874 \& getfsspec() mbsrtowcs() ungetwc()
875 \& getgrent() mbstowcs() unsetenv()
876 \& getgrent_r() mbtowc() updwtmp()
877 \& getgrgid() mcheck() utmpname()
878 \& getgrgid_r() mcheck_check_all() va_arg()
879 \& getgrnam() mcheck_pedantic() valloc()
880 \& getgrnam_r() mktime() vasprintf()
881 \& getgrouplist() mprobe() vdprintf()
882 \& gethostbyaddr() mrand48() verr()
883 \& gethostbyaddr_r() mrand48_r() verrx()
884 \& gethostbyname() mtrace() versionsort()
885 \& gethostbyname2() muntrace() vfprintf()
886 \& gethostbyname2_r() nan() vfscanf()
887 \& gethostbyname_r() nanf() vfwprintf()
888 \& gethostent() nanl() vprintf()
889 \& gethostent_r() newlocale() vscanf()
890 \& gethostid() nftw() vsnprintf()
891 \& getlogin() nl_langinfo() vsprintf()
892 \& getlogin_r() nrand48() vsscanf()
893 \& getmntent() nrand48_r() vswprintf()
894 \& getmntent_r() openpty() vsyslog()
895 \& getnameinfo() perror() vwarn()
896 \& getnetbyaddr() posix_fallocate() vwarnx()
897 \& getnetbyaddr_r() printf() vwprintf()
898 \& getnetbyname() profil() warn()
899 \& getnetbyname_r() psiginfo() warnx()
900 \& getnetent() psignal() wcrtomb()
901 \& getnetent_r() ptsname() wcscasecmp()
902 \& getnetgrent() putchar_unlocked() wcschr()
903 \& getnetgrent_r() putc_unlocked() wcscoll()
904 \& getopt() putenv() wcsftime()
905 \& getopt_long() putpwent() wcsncasecmp()
906 \& getopt_long_only() putspent() wcsnrtombs()
907 \& getpass() pututline() wcsrchr()
908 \& getprotobyname() pututxline() wcsrtombs()
909 \& getprotobyname_r() putwc() wcstod()
910 \& getprotobynumber() putwchar() wcstof()
911 \& getprotobynumber_r() putwchar_unlocked() wcstoimax()
912 \& getprotoent() putwc_unlocked() wcstold()
913 \& getprotoent_r() pvalloc() wcstombs()
914 \& getpw() qecvt() wcstoumax()
915 \& getpwent() qfcvt() wcswidth()
916 \& getpwent_r() querylocale() wcsxfrm()
917 \& getpwnam() rand() wctob()
918 \& getpwnam_r() random_r() wctomb()
919 \& getpwuid() rcmd() wctrans()
920 \& getpwuid_r() rcmd_af() wctype()
921 \& getrpcbyname() readdir() wcwidth()
922 \& getrpcbyname_r() readdir64() wordexp()
923 \& getrpcbynumber() readdir64_r() wprintf()
924 \& getrpcbynumber_r() readdir_r() wscanf()
925 \& getrpcent() re_comp() wsetlocale()
926 .Ve
927 .PP
928 (If you know of additional functions that are unsafe on some platform or
929 another, notify us via filing a bug report at
930 <https://github.com/Perl/perl5/issues>.)
931 .PP
932 Some of these are safe under MULTIPLICITY, problematic only under threading.
933 If a use doesn\*(Aqt appear in the above list, we think it is MULTIPLICITY
934 and thread\-safe on all platforms.
935 .PP
936 All the uses listed above are function calls, except for these:
937 .PP
938 .Vb 1
939 \& daylight MB_CUR_MAX timezone tzname
940 .Ve
941 .PP
942 There are three main approaches to coping with issues involving these
943 constructs, each suitable for different circumstances:
944 .IP \(bu 4
945 Don\*(Aqt use them. Some of them have preferred alternatives. Use the list
946 above in "libc functions to avoid" to replace your uses with ones
947 that are thread\-friendly. For example I/O, should be done via
948 perlapio.
949 .Sp
950 If you must use them, many, but not all, of them will be ok as long as
951 their use is confined to a single thread that has no interaction with
952 conflicting uses in other threads. You will need to closely examine
953 their man pages for this, and be aware that vendor documentation is
954 often imprecise.
955 .IP \(bu 4
956 Do all your business before any other code can change things. If you
957 make changes, change back before returning.
958 .IP \(bu 4
959 Save the result of a query of global information to a per\-instance area
960 before allowing another instance to execute. Then you can work on it at
961 your leisure. This might be an automatic C variable for non\-pointers,
962 or something as described above in
963 \&\f(CW\*(C`"Safely Storing Static Data in XS" in perlxs\*(C'\fR.
964 .PP
965 Without threading, you don\*(Aqt have to worry about being interrupted by
966 the system giving control to another thread. With threading, you will
967 have to uses mutexes, and be concerned with the possibility of deadlock.
968 .SS "Functions always unsuitable for use under multi\-threads"
969 .IX Subsection "Functions always unsuitable for use under multi-threads"
970 A few functions are considered totally unsuited for use in a multi\-thread
971 environment. These must be called only during single\-thread operation.
972 .PP
973 .Vb 6
974 \& endusershell() @getaliasent() muntrace() rexec()
975 \& ether_aton() @getrpcbyname() profil() rexec_af()
976 \& ether_ntoa() @getrpcbynumber() rcmd() setusershell()
977 \& fts_children() @getrpcent() rcmd_af() ttyslot()
978 \& fts_read() getusershell() re_comp()
979 \& @getaliasbyname() mtrace() re_exec()
980 .Ve
981 .PP
982 \&\f(CW\*(C`@\*(C'\fR above marks the functions for which there are preferred alternatives
983 available on some platforms, and those alternatives may be suitable for
984 multi\-thread use.
985 .SS "Functions which must be called at least once before starting threads"
986 .IX Subsection "Functions which must be called at least once before starting threads"
987 Some functions perform initialization on their first call that must be done
988 while still in a single\-thread environment, but subsequent calls are
989 thread\-safe when executed in a critical section.
990 Therefore, they must be called at least once before switching to
991 multi\-threads:
992 .PP
993 .Vb 2
994 \& getutent() getutline() getutxid() mallinfo() valloc()
995 \& getutid() getutxent() getutxline() pvalloc()
996 .Ve
997 .SS "Functions that are thread\-safe when called with appropriate arguments"
998 .IX Subsection "Functions that are thread-safe when called with appropriate arguments"
999 Some of the functions are thread\-safe if called with arguments that
1000 comply with certain (easily met) restrictions. These are:
1001 .PP
1002 .Vb 3
1003 \& ctermid() mbrlen() mbsrtowcs() wcrtomb()
1004 \& cuserid() mbrtowc() tmpnam() wcsnrtombs()
1005 \& error_at_line() mbsnrtowcs() va_arg() wcsrtombs()
1006 .Ve
1007 .PP
1008 See the man pages of each for details. (For completeness, the list
1009 includes functions that you shouldn\*(Aqt be using anyway because of other
1010 reasons.)
1011 .SS "Functions vulnerable to signals"
1012 .IX Subsection "Functions vulnerable to signals"
1013 Some functions are vulnerable to asynchronous signals. These are:
1014 .PP
1015 .Vb 3
1016 \& getlogin() getutid() getutxid() login() pututline() updwtmp()
1017 \& getlogin_r() getutline() getutxline() logout() pututxline() wordexp()
1018 \& getutent() getutxent() glob() logwtmp() sleep()
1019 .Ve
1020 .PP
1021 Some libc\*(Aqs implement \*(\fBAqsystem()\fR\*(Aq thread\-safely. But in others, it also
1022 has signal issues.
1023 .SS "General issues with thread\-safety"
1024 .IX Subsection "General issues with thread-safety"
1025 Some libc functions use and/or modify a global state, such as a database.
1026 The libc functions presume that there is only one instance at a time
1027 operating on that database. Unpredictable results occur if more than one
1028 does, even if the database is not changed. For example, typically there is
1029 a global iterator for such a data base and that iterator is maintained by
1030 libc, so that each new read from any instance advances it, meaning that no
1031 instance will see all the entries. The only way to make these thread\-safe
1032 is to have an exclusive lock on a mutex from the open call through the
1033 close. You are advised to not use such databases from more than one
1034 instance at a time.
1035 .PP
1036 Other examples of functions that use a global state include pseudo\-random
1037 number generators. Some libc implementations of \*(\fBAqrand()\fR\*(Aq, for example, may
1038 share the data across threads; and others may have per\-thread data. The
1039 shared ones will have unreproducible results, as the threads will vary in
1040 their timings and interactions. This may be what you want; or it may not
1041 be. (This particular function is a candidate to be removed from the POSIX
1042 Standard because of these issues.)
1043 .PP
1044 Functions that output to a stream also are considered thread\-unsafe when
1045 locking is not done. But the typical consequences are just that the data
1046 is output in an unpredictable order; that outcome may be totally
1047 acceptable to you.
1048 .PP
1049 Since the current working directory is global to a process, all
1050 instances depend on it. One instance doing a \fBchdir\fR\|(2) affects all the
1051 other instances. In a multi\-threaded environment, any libc call that
1052 expects the directory to not change for the duration of its execution
1053 will have undefined results if another thread interrupts it at just the
1054 wrong time and changes the directory. The man pages only list one such
1055 call, \fBnftw()\fR. But there may be other issues lurking.
1056 .SS "Reentrant equivalent functions"
1057 .IX Subsection "Reentrant equivalent functions"
1058 Some functions that are problematic with regard to MULTIPLICITY have
1059 reentrant versions (on some or all platforms) that are better suited,
1060 with fewer (perhaps no) races when run under threads.
1061 .PP
1062 Some of these reentrant functions that are available on all platforms
1063 should always be used anyway; they are in the lists directly under
1064 "libc functions to avoid".
1065 .PP
1066 Others may not be available on some platforms, or have issues that make
1067 them undesirable to use even when they are available. Or it may just be
1068 more complicated and tedious to use the reentrant version. For these,
1069 perl has a mechanism for automatically substituting that reentrant
1070 version when available and desirable, while hiding the complications
1071 from your code. This feature is enabled by default for code in the Perl
1072 core and its extensions. To enable it in other XS modules,
1073 .PP
1074 .Vb 1
1075 \& #define PERL_REENTRANT
1076 .Ve
1077 .PP
1078 It is simpler for you to use the unpreferred version in your code, and
1079 rely on this feature to do the better thing, in part because no
1080 substitution is done if the alternative is not available or desirable on
1081 the platform, nor if threads aren\*(Aqt enabled. You just write as if there
1082 weren\*(Aqt threads, and you get the better behavior without having to think
1083 about it.
1084 .PP
1085 On some platforms the safer library functions may fail if the result
1086 buffer is too small (for example the user group databases may be rather
1087 large, and the reentrant functions may have to carry around a full
1088 snapshot of those databases). Perl will start with a small buffer, but
1089 keep retrying and growing the result buffer until the result fits. If
1090 this limitless growing sounds bad for security or memory consumption
1091 reasons you can recompile Perl with \f(CW\*(C`PERL_REENTRANT_MAXSIZE\*(C'\fR #defined
1092 to the maximum number of bytes you will allow.
1093 .PP
1094 Below is a list of the non\-reentrant functions and their reentrant
1095 alternatives. This substitution is done even on functions that you
1096 shouldn\*(Aqt be using in the first place. These are marked by a \f(CW\*(C`*\*(C'\fR. You
1097 should instead use the alternate given in the lists directly under
1098 "libc functions to avoid".
1099 .PP
1100 Even so, some of the preferred alternatives are considered obsolete or
1101 otherwise unwise to use on some platforms. These are marked with a \*(Aq?\*(Aq.
1102 Also, some alternatives aren\*(Aqt Perl\-defined functions and aren\*(Aqt in
1103 the POSIX Standard, so won\*(Aqt be widely available. These are marked with
1104 \&\*(Aq~\*(Aq. (Remember that the automatic substitution only happens when they
1105 are available and desirable, so you can just use the unpreferred
1106 alternative.)
1107 .PP
1108 .Vb 10
1109 \& *asctime() ?asctime_r()
1110 \& crypt() ~crypt_r()
1111 \& ctermid() ~ctermid_r()
1112 \& *ctime() ?ctime_r()
1113 \& endgrent() ?~endgrent_r()
1114 \& endhostent() ?~endhostent_r()
1115 \& endnetent() ?~endnetent_r()
1116 \& endprotoent() ?~endprotoent_r()
1117 \& endpwent() ?~endpwent_r()
1118 \& endservent() ?~endservent_r()
1119 \& getgrent() ~getgrent_r()
1120 \& getgrgid() getgrgid_r()
1121 \& getgrnam() getgrnam_r()
1122 \& gethostbyaddr() ~gethostbyaddr_r()
1123 \& gethostbyname() ~gethostbyname_r()
1124 \& gethostent() ~gethostent_r()
1125 \& getlogin() getlogin_r()
1126 \& getnetbyaddr() ~getnetbyaddr_r()
1127 \& getnetbyname() ~getnetbyname_r()
1128 \& getnetent() ~getnetent_r()
1129 \& getprotobyname() ~getprotobyname_r()
1130 \& getprotobynumber() ~getprotobynumber_r()
1131 \& getprotoent() ~getprotoent_r()
1132 \& getpwent() ~getpwent_r()
1133 \& getpwnam() getpwnam_r()
1134 \& getpwuid() getpwuid_r()
1135 \& getservbyname() ~getservbyname_r()
1136 \& getservbyport() ~getservbyport_r()
1137 \& getservent() ~getservent_r()
1138 \& getspnam() ~getspnam_r()
1139 \& gmtime() gmtime_r()
1140 \& localtime() localtime_r()
1141 \& readdir() ?readdir_r()
1142 \& readdir64() ~readdir64_r()
1143 \& setgrent() ?~setgrent_r()
1144 \& sethostent() ?~sethostent_r()
1145 \& *setlocale() ?~setlocale_r()
1146 \& setnetent() ?~setnetent_r()
1147 \& setprotoent() ?~setprotoent_r()
1148 \& setpwent() ?~setpwent_r()
1149 \& setservent() ?~setservent_r()
1150 \& *strerror() strerror_r()
1151 \& *tmpnam() ~tmpnam_r()
1152 \& ttyname() ttyname_r()
1153 .Ve
1154 .PP
1155 The Perl\-furnished items are documented in perlapi.
1156 .PP
1157 The bottom line is:
1158 .ie n .IP "For items marked ""*""" 4
1159 .el .IP "For items marked \f(CW*\fR" 4
1160 .IX Item "For items marked *"
1161 Replace all uses of these with the preferred alternative given in the
1162 lists directly under "libc functions to avoid".
1163 .IP "For the remaining items" 4
1164 .IX Item "For the remaining items"
1165 If you really need to use these functions, you have two choices:
1166 .RS 4
1167 .IP "If you #define PERL_REENTRANT" 4
1168 .IX Item "If you #define PERL_REENTRANT"
1169 Use the function in the first column as\-is, and let perl do the work of
1170 substituting the function in the right column if available on the
1171 platform, and it is deemed suitable for use.
1172 .Sp
1173 You should look at the man pages for both versions to find any other
1174 gotchas.
1175 .IP "If you don\*(Aqt enable automatic substitution" 4
1176 .IX Item "If you don't enable automatic substitution"
1177 You should examine the application\*(Aqs code to determine if the column 1
1178 function presents a real problem under threads given the circumstances
1179 it is used in. You can go directly to the column 2 replacement, but
1180 beware of the ones that are marked. Some of those may be nonexistent or
1181 flaky on some platforms.
1182 .RE
1183 .RS 4
1184 .RE
1185 .SS "Functions that need the environment to be constant"
1186 .IX Subsection "Functions that need the environment to be constant"
1187 Since the environment is global to a process, all instances depend on
1188 it. One instance changing the environment affects all the other
1189 instances. Under threads, any libc call that expects the environment to
1190 not change for the duration of its execution will have undefined results
1191 if another thread interrupts it at just the wrong time and changes it.
1192 These are the functions that the man pages list as being sensitive to
1193 that.
1194 .PP
1195 .Vb 10
1196 \& catopen() gethostbyname2() newlocale()
1197 \& ctime() gethostbyname2_r() regerror()
1198 \& ctime_r() gethostbyname_r() secure_getenv()
1199 \& endhostent() gethostent() sethostent()
1200 \& endhostent_r() gethostent_r() sethostent_r()
1201 \& endnetent() gethostid() setlocale()
1202 \& endnetent_r() getnameinfo() setlocale_r()
1203 \& execlp() getnetbyname() setnetent()
1204 \& execvp() getnetent() setnetent_r()
1205 \& execvpe() getopt() strftime()
1206 \& fnmatch() getopt_long() strptime()
1207 \& getaddrinfo() getopt_long_only() sysconf()
1208 \& get_current_dir_name() getrpcport() syslog()
1209 \& getdate() glob() tempnam()
1210 \& getdate_r() gmtime() timegm()
1211 \& getenv() gmtime_r() timelocal()
1212 \& gethostbyaddr() localtime() tzset()
1213 \& gethostbyaddr_r() localtime_r() vsyslog()
1214 \& gethostbyname() mktime()
1215 .Ve
1216 .PP
1217 Many of these functions are problematic under threads for other reasons
1218 as well. See the man pages for any you use.
1219 .PP
1220 Perl defines mutexes \f(CW\*(C`ENV_READ_LOCK\*(C'\fR and \f(CW\*(C`ENV_READ_UNLOCK\*(C'\fR with which
1221 to wrap calls to these functions. You need to consider the possibility
1222 of deadlock. It is expected that a different mechanism will be in place
1223 and preferred for Perl v5.42.
1224 .SS "Locale\-specific issues"
1225 .IX Subsection "Locale-specific issues"
1226 C language programs originally had a single locale global to the entire
1227 process. This was later found to be inadequate for many purposes, so later
1228 extensions changed that, first with Windows, and then POSIX 2008. In
1229 Windows, you can change any thread at any time to operate either with a
1230 per\-thread locale, or with the global one, using a special new libc
1231 function. In POSIX, the original API operates only on the global
1232 locale, but there is an entirely new API to manipulate either per\-thread
1233 locales or the global one. As with Windows (but using the new API), a
1234 thread can be switched at any time to operate on the global locale, or a
1235 per\-thread one.
1236 .PP
1237 When one instance changes the global locale, all other instances using
1238 the global locale are affected. Almost all the locale\-related functions
1239 in the list directly under "Dealing with embedded perls and threads"
1240 have undefined behavior if another thread interrupts their execution and
1241 changes the locale. Under threads, another thread could do exactly that.
1242 .PP
1243 But, on systems that have per\-thread locales, starting with Perl v5.28,
1244 perl uses them after initialization; the global locale is not used
1245 except if XS code has called \f(CWswitch_to_global_locale()\fR. Doing so
1246 affects only the thread that called it. If a maximum of one instance is
1247 using the global locale, no other instances are affected, the locale of
1248 concurrently executing functions in other threads is not changed, and
1249 this becomes a non\-issue. The C preprocessor symbol
1250 \&\f(CW\*(C`USE_THREAD_SAFE_LOCALE\*(C'\fR will be defined if per\-thread locales are
1251 available and perl has been compiled to use them. The implementation of
1252 per\-thread locales on some platforms, like most *BSD\-based ones, is so
1253 buggy that the perl hints files for them deliberately turn off the
1254 possibility of using them.
1255 .PP
1256 The converse is that on systems with only a global locale, having
1257 different threads using different locales is not likely to work well;
1258 and changing the locale is dangerous, often leading to crashes.
1259 .PP
1260 Perl has extensive code to work as well as possible on both types of
1261 systems. You should always use \f(CWPerl_setlocale()\fR to change and query
1262 the locale, as it portably works across the range of possibilities.
1263 .SH "SEE ALSO"
1264 .IX Header "SEE ALSO"
1265 perlapi, perlapio, perlguts, perlxs