1 /* Copyright (C) 1991-2022 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
3
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
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
8
9 The GNU C Library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Lesser General Public License for more details.
13
14 You should have received a copy of the GNU Lesser General Public
15 License along with the GNU C Library; if not, see
16 <https://www.gnu.org/licenses/>. */
17
18 #include <errno.h>
19 #include <stdio.h>
20 #include <string.h>
21 #include <unistd.h>
22 #include <wchar.h>
23 #include "libioP.h"
24
25 static void
perror_internal(FILE * fp,const char * s,int errnum)26 perror_internal (FILE *fp, const char *s, int errnum)
27 {
28 char buf[1024];
29 const char *colon;
30 const char *errstring;
31
32 if (s == NULL || *s == '\0')
33 s = colon = "";
34 else
35 colon = ": ";
36
37 errstring = __strerror_r (errnum, buf, sizeof buf);
38
39 (void) __fxprintf (fp, "%s%s%s\n", s, colon, errstring);
40 }
41
42
43 /* Print a line on stderr consisting of the text in S, a colon, a space,
44 a message describing the meaning of the contents of `errno' and a newline.
45 If S is NULL or "", the colon and space are omitted. */
46 void
perror(const char * s)47 perror (const char *s)
48 {
49 int errnum = errno;
50 FILE *fp;
51 int fd = -1;
52
53
54 /* The standard says that 'perror' must not change the orientation
55 of the stream. What is supposed to happen when the stream isn't
56 oriented yet? In this case we'll create a new stream which is
57 using the same underlying file descriptor. */
58 if (__builtin_expect (_IO_fwide (stderr, 0) != 0, 1)
59 || (fd = __fileno (stderr)) == -1
60 || (fd = __dup (fd)) == -1
61 || (fp = fdopen (fd, "w+")) == NULL)
62 {
63 if (__glibc_unlikely (fd != -1))
64 __close (fd);
65
66 /* Use standard error as is. */
67 perror_internal (stderr, s, errnum);
68 }
69 else
70 {
71 /* We don't have to do any special hacks regarding the file
72 position. Since the stderr stream wasn't used so far we just
73 write to the descriptor. */
74 perror_internal (fp, s, errnum);
75
76 if (_IO_ferror_unlocked (fp))
77 stderr->_flags |= _IO_ERR_SEEN;
78
79 /* Close the stream. */
80 fclose (fp);
81 }
82 }
83 libc_hidden_def (perror)
84