4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License, Version 1.0 only
6 * (the "License"). You may not use this file except in compliance
9 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10 * or http://www.opensolaris.org/os/licensing.
11 * See the License for the specific language governing permissions
12 * and limitations under the License.
14 * When distributing Covered Code, include this CDDL HEADER in each
15 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16 * If applicable, add the following below this CDDL HEADER, with the
17 * fields enclosed by brackets "[]" replaced with your own identifying
18 * information: Portions Copyright [yyyy] [name of copyright owner]
23 * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
24 * Use is subject to license terms.
27 #pragma ident "%Z%%M% %I% %E% SMI"
30 * Utility functions for buffering output to stdout, stderr while
31 * process is grabbed. Prevents infamous deadlocks due to pfiles `pgrep xterm`
38 static int cached_stdout_fd
= -1;
39 static int cached_stderr_fd
= -1;
40 static int initialized
= 0;
42 static char stdout_name
[] = "/tmp/.stdoutXXXXXX";
43 static char stderr_name
[] = "/tmp/.stderrXXXXXX";
50 (void) fflush(stdout
);
51 (void) fflush(stderr
);
53 if ((cached_stdout_fd
= dup(1)) < 0) {
57 if ((cached_stderr_fd
= dup(2)) < 0) {
58 (void) close(cached_stdout_fd
);
62 if ((fd
= mkstemp(stdout_name
)) < 0) {
63 (void) close(cached_stdout_fd
);
64 (void) close(cached_stderr_fd
);
68 (void) unlink(stdout_name
);
70 if (dup2(fd
, 1) < 0) {
72 (void) close(cached_stdout_fd
);
73 (void) close(cached_stderr_fd
);
80 if ((fd
= mkstemp(stderr_name
)) < 0) {
81 (void) dup2(cached_stdout_fd
, 1);
82 (void) close(cached_stdout_fd
);
83 (void) close(cached_stderr_fd
);
87 (void) unlink(stderr_name
);
89 if (dup2(fd
, 2) < 0) {
91 (void) dup2(cached_stdout_fd
, 1);
92 (void) close(cached_stdout_fd
);
93 (void) dup2(cached_stderr_fd
, 2);
94 (void) close(cached_stderr_fd
);
107 copy_fd(int out
, FILE *in
, size_t len
)
114 while (len
> 0 && !errors
) {
115 rlen
= (len
> sizeof (buffer
)) ? sizeof (buffer
) : len
;
116 alen
= read(fileno(in
), buffer
, rlen
);
118 if (write(out
, buffer
, alen
) < alen
)
131 proc_flushstdio(void)
137 * flush any pending IO
143 (void) fflush(stdout
);
144 (void) fflush(stderr
);
146 if ((len
= ftell(stdout
)) > 0)
147 errors
+= copy_fd(cached_stdout_fd
, stdout
, len
);
150 if ((len
= ftell(stderr
)) > 0)
151 errors
+= copy_fd(cached_stderr_fd
, stderr
, len
);
153 return (errors
?-1:0);
162 if (proc_flushstdio() != 0)
165 (void) dup2(cached_stdout_fd
, 1);
166 (void) close(cached_stdout_fd
);
167 (void) dup2(cached_stderr_fd
, 2);
168 (void) close(cached_stderr_fd
);