Fix sys/ucontext.h namespace from signal.h etc. inclusion (bug 21457).
[glibc.git] / stdio-common / perror.c
blobd109c63607bf8e0d98f2b85f594932f633f96066
1 /* Copyright (C) 1991-2017 Free Software Foundation, Inc.
2 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
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
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.
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 <http://www.gnu.org/licenses/>. */
18 #include <errno.h>
19 #include <stdio.h>
20 #include <string.h>
21 #include <unistd.h>
22 #include <wchar.h>
23 #include "libioP.h"
25 static void
26 perror_internal (FILE *fp, const char *s, int errnum)
28 char buf[1024];
29 const char *colon;
30 const char *errstring;
32 if (s == NULL || *s == '\0')
33 s = colon = "";
34 else
35 colon = ": ";
37 errstring = __strerror_r (errnum, buf, sizeof buf);
39 (void) __fxprintf (fp, "%s%s%s\n", s, colon, errstring);
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
47 perror (const char *s)
49 int errnum = errno;
50 FILE *fp;
51 int fd = -1;
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)
63 if (__glibc_unlikely (fd != -1))
64 __close (fd);
66 /* Use standard error as is. */
67 perror_internal (stderr, s, errnum);
69 else
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);
76 if (_IO_ferror_unlocked (fp))
77 stderr->_flags |= _IO_ERR_SEEN;
79 /* Close the stream. */
80 fclose (fp);
83 libc_hidden_def (perror)