8 register STIO *stio = stab_io(stab);
9 char *myname = savestr(name);
13 char mode[3]; /* stdio file mode ("r\0" or "r+\0") */
14 FILE *saveifp = Nullfp;
15 FILE *saveofp = Nullfp;
18 mode[0] = mode[1] = mode[2] = '\0';
20 forkprocess = 1; /* assume true if no fork */
21 while (len && isSPACE(name[len-1]))
24 stio = stab_io(stab) = stio_new();
26 fd = fileno(stio->ifp);
27 if (stio->type == '-')
29 else if (fd <= maxsysfd) {
32 savetype = stio->type;
35 else if (stio->type == '|')
36 result = mypclose(stio->ifp);
37 else if (stio->ifp != stio->ofp) {
39 result = fclose(stio->ofp);
40 fclose(stio->ifp); /* clear stdio, fd already closed */
43 result = fclose(stio->ifp);
46 result = fclose(stio->ifp);
47 if (result == EOF && fd > maxsysfd)
48 fprintf(stderr,"Warning: unable to close filehandle %s properly.\n",
50 stio->ofp = stio->ifp = Nullfp;
52 if (*name == '+' && len > 1 && name[len-1] != '|') { /* scary */
64 for (name++; isSPACE(*name); name++) ;
66 TAINT_PROPER("piped open");
67 fp = mypopen(name,"w");
70 else if (*name == '>') {
74 mode[0] = stio->type = 'a';
83 while (isSPACE(*name))
88 stab = stabent(name,FALSE);
89 if (!stab || !stab_io(stab)) {
95 if (stab_io(stab) && stab_io(stab)->ifp) {
96 fd = fileno(stab_io(stab)->ifp);
97 if (stab_io(stab)->type == 's')
103 if (!(fp = fdopen(fd = dup(fd),mode))) {
108 while (isSPACE(*name))
110 if (strEQ(name,"-")) {
115 fp = fopen(name,mode);
123 while (isSPACE(*name))
127 if (strEQ(name,"-")) {
132 fp = fopen(name,mode);
134 else if (name[len-1] == '|') {
136 TAINT_PROPER("piped open");
138 while (len && isSPACE(name[len-1]))
141 for (; isSPACE(*name); name++) ;
142 fp = mypopen(name,"r");
148 for (; isSPACE(*name); name++) ;
149 if (strEQ(name,"-")) {
154 fp = fopen(name,"r");
158 if (dowarn && stio->type == '<' && index(name, '\n'))
159 warn(warn_nl, "open");
165 stio->type != '|' && stio->type != '-') {
166 if (fstat(fileno(fp),&statbuf) < 0) {
170 if (S_ISSOCK(statbuf.st_mode))
171 stio->type = 's'; /* in case a socket was passed in to us */
175 !(statbuf.st_mode & S_IFMT)
180 int buflen = sizeof tokenbuf;
181 if (getsockname(fileno(fp), tokenbuf, &buflen) >= 0
182 || errno != ENOTSOCK)
183 stio->type = 's'; /* some OS's return 0 on fstat()ed socket */
184 /* but some return 0 for streams too, sigh */
188 if (saveifp) { /* must use old fp? */
189 fd = fileno(saveifp);
191 fflush(saveofp); /* emulate fclose() */
192 if (saveofp != saveifp) { /* was a socket? */
198 if (fd != fileno(fp)) {
202 dup2(fileno(fp), fd);
203 TARG = afetch(fdpid,fileno(fp),TRUE);
204 pid = TARG->str_u.str_useful;
205 TARG->str_u.str_useful = 0;
206 TARG = afetch(fdpid,fd,TRUE);
207 TARG->str_u.str_useful = pid;
214 #if defined(HAS_FCNTL) && defined(F_SETFD)
216 fcntl(fd,F_SETFD,fd > maxsysfd);
220 if (stio->type == 's'
221 || (stio->type == '>' && S_ISCHR(statbuf.st_mode)) ) {
222 if (!(stio->ofp = fdopen(fileno(fp),"w"))) {
236 stio->type = savetype;