1 /* $Header: /p/tcsh/cvsroot/tcsh/sh.c,v 3.145 2009/06/25 21:15:37 christos Exp $ */
3 * sh.c: Main shell routines
6 * Copyright (c) 1980, 1991 The Regents of the University of California.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 #define EXTERN /* Intern */
38 "@(#) Copyright (c) 1991 The Regents of the University of California.\n\
39 All rights reserved.\n";
42 RCSID("$tcsh: sh.c,v 3.145 2009/06/25 21:15:37 christos Exp $")
48 extern int MapsAreInited
;
49 extern int NLSMapsAreInited
;
54 * Bill Joy, UC Berkeley, California, USA
55 * October 1978, May 1980
57 * Jim Kulp, IIASA, Laxenburg, Austria
60 * Filename recognition added:
61 * Ken Greer, Ind. Consultant, Palo Alto CA
64 * Karl Kleinpaste, Computer Consoles, Inc.
65 * Added precmd, periodic/tperiod, prompt changes,
66 * directory stack hack, and login watch.
67 * Sometime March 1983 - Feb 1984.
69 * Added scheduled commands, including the "sched" command,
70 * plus the call to sched_run near the precmd et al
72 * Upgraded scheduled events for running events while
73 * sitting idle at command input.
75 * Paul Placeway, Ohio State
76 * added stuff for running with twenex/inputl 9 Oct 1984.
78 * ported to Apple Unix (TM) (OREO) 26 -- 29 Jun 1987
81 jmp_buf_t reslab INIT_ZERO_STRUCT
;
83 static const char tcshstr
[] = "tcsh";
85 struct sigaction parintr
; /* Parents interrupt catch */
86 struct sigaction parterm
; /* Parents terminate catch */
93 int use_fork
= 0; /* use fork() instead of vfork()? */
96 * Magic pointer values. Used to specify other invalid conditions aside
100 Char
*INVPTR
= &INVCHAR
;
101 Char
**INVPPTR
= &INVPTR
;
104 static int mflag
= 0;
105 static int prompt
= 1;
113 static time_t chktim
; /* Time mail last checked */
118 * This preserves the input state of the shell. It is used by
119 * st_save and st_restore to manupulate shell state.
128 struct whyle
*whyles
;
145 static int srccat (Char
*, Char
*);
147 static int srcfile (const char *, int, int, Char
**);
149 int srcfile (const char *, int, int, Char
**);
150 #endif /*WINNT_NATIVE*/
151 static void srcunit (int, int, int, Char
**);
152 static void mailchk (void);
153 #ifndef _PATH_DEFPATH
154 static Char
**defaultpath (void);
156 static void record (void);
157 static void st_save (struct saved_state
*, int, int,
159 static void st_restore (void *);
161 int main (int, char **);
164 main(int argc
, char **argv
)
167 volatile int nexececho
= 0;
169 volatile int nverbose
= 0;
170 volatile int rdirs
= 0;
180 struct sigaction oparintr
;
184 #endif /* WINNT_NATIVE */
185 #if defined(NLS_CATALOGS) && defined(LC_MESSAGES)
186 (void) setlocale(LC_MESSAGES
, "");
187 #endif /* NLS_CATALOGS && LC_MESSAGES */
191 (void) setlocale(LC_CTYPE
, ""); /* for iscntrl */
192 # endif /* LC_CTYPE */
198 mal_setstatsfile(fdopen(dmove(xopen("/tmp/tcsh.trace",
199 O_WRONLY
|O_CREAT
|O_LARGEFILE
, 0666), 25), "w"));
201 #endif /* MALLOC_TRACE */
203 #if !(defined(BSDTIMES) || defined(_SEQUENT_)) && defined(POSIX)
205 clk_tck
= (clock_t) sysconf(_SC_CLK_TCK
);
206 # else /* ! _SC_CLK_TCK */
209 # else /* !CLK_TCK */
211 # endif /* CLK_TCK */
212 # endif /* _SC_CLK_TCK */
213 #endif /* !BSDTIMES && POSIX */
215 settimes(); /* Immed. estab. timing base */
221 * Make sure we have 0, 1, 2 open
222 * Otherwise `` jobs will not work... (From knaff@poly.polytechnique.fr)
226 if ((f
= xopen(_PATH_DEVNULL
, O_RDONLY
|O_LARGEFILE
)) == -1 &&
227 (f
= xopen("/", O_RDONLY
|O_LARGEFILE
)) == -1)
233 osinit(); /* Os dependent initialization */
239 t
= strrchr(argv
[0], '/');
242 char *s
= strrchr(argv
[0], '\\');
246 #endif /* WINNT_NATIVE */
247 t
= t
? t
+ 1 : argv
[0];
249 progname
= strsave((t
&& *t
) ? t
: tcshstr
); /* never want a null */
250 tcsh
= strcmp(progname
, tcshstr
) == 0;
254 * Initialize non constant strings
257 STR_BSHELL
= SAVE(_PATH_BSHELL
);
260 STR_SHELLPATH
= SAVE(_PATH_TCSHELL
);
263 STR_SHELLPATH
= SAVE(_PATH_CSHELL
);
266 STR_environ
= blk2short(environ
);
267 environ
= short2blk(STR_environ
); /* So that we can free it */
268 STR_WORD_CHARS
= SAVE(WORD_CHARS
);
274 word_chars
= STR_WORD_CHARS
;
275 bslash_quote
= 0; /* PWP: do tcsh-style backslash quoting? */
277 /* Default history size to 100 */
278 setcopy(STRhistory
, str2short("100"), VAR_READWRITE
);
281 ffile
= SAVE(tempv
[0]);
283 if (eq(ffile
, STRaout
)) /* A.out's are quittable */
290 * We are a login shell if: 1. we were invoked as -<something> with
291 * optional arguments 2. or we were invoked only with the -l flag
293 loginsh
= (**tempv
== '-') || (argc
== 2 &&
294 tempv
[1][0] == '-' && tempv
[1][1] == 'l' &&
295 tempv
[1][2] == '\0');
297 /* No better way to find if we are a login shell */
299 loginsh
= (argc
== 1 && getppid() == 1);
300 **tempv
= '-'; /* Avoid giving VMS an acidic stomach */
302 #endif /* _VMS_POSIX */
304 if (loginsh
&& **tempv
!= '-') {
308 * Mangle the argv space
313 argv0
= strspl("-", *tempv
);
318 (void) time(&chktim
);
323 NoNLSRebind
= getenv("NOREBIND") != NULL
;
327 # endif /* SETLOCALEBUG */
328 (void) setlocale(LC_ALL
, "");
330 (void) setlocale(LC_COLLATE
, "");
334 # endif /* SETLOCALEBUG */
337 # endif /* STRCOLLBUG */
342 for (k
= 0200; k
<= 0377 && !Isprint(CTL_ESC(k
)); k
++)
344 AsciiOnly
= MB_CUR_MAX
== 1 && k
> 0377;
347 AsciiOnly
= getenv("LANG") == NULL
&& getenv("LC_CTYPE") == NULL
;
349 if (MapsAreInited
&& !NLSMapsAreInited
)
354 * Initialize for periodic command intervals. Also, initialize the dummy
355 * tty list for login-watch.
357 (void) time(&t_period
);
360 #endif /* !HAVENOUTMP */
364 * From: Jim Pace <jdp@research.att.com>
365 * tcsh does not work properly on the alliants through an rlogin session.
366 * The shell generally hangs. Also, reference to the controlling terminal
367 * does not work ( ie: echo foo > /dev/tty ).
369 * A security feature was added to rlogind affecting FX/80's Concentrix
370 * from revision 5.5.xx upwards (through 5.7 where this fix was implemented)
371 * This security change also affects the FX/2800 series.
372 * The security change to rlogind requires the process group of an rlogin
373 * session become disassociated with the tty in rlogind.
375 * The changes needed are:
376 * 1. set the process group
377 * 2. reenable the control terminal
379 if (loginsh
&& isatty(SHIN
)) {
380 ttyn
= ttyname(SHIN
);
382 SHIN
= xopen(ttyn
, O_RDWR
|O_LARGEFILE
);
384 (void) ioctl (SHIN
, TIOCSPGRP
, (ioctl_t
) &shpgrp
);
385 (void) setpgid(0, shpgrp
);
390 * Move the descriptors to safe places. The variable didfds is 0 while we
391 * have only FSH* to work with. When didfds is true, we have 0,1,2 and
392 * prefer to use these.
397 * Get and set the tty now
399 if ((ttyn
= ttyname(SHIN
)) != NULL
) {
401 * Could use rindex to get rid of other possible path components, but
402 * hpux preserves the subdirectory /pty/ when storing the tty name in
403 * utmp, so we keep it too.
405 if (strncmp(ttyn
, "/dev/", 5) == 0)
406 setv(STRtty
, cp
= SAVE(ttyn
+ 5), VAR_READWRITE
);
408 setv(STRtty
, cp
= SAVE(ttyn
), VAR_READWRITE
);
411 setv(STRtty
, cp
= SAVE(""), VAR_READWRITE
);
413 * Initialize the shell variables. ARGV and PROMPT are initialized later.
414 * STATUS is also munged in several places. CHILD is munged when
419 * 7-10-87 Paul Placeway autologout should be set ONLY on login shells and
420 * on shells running as root. Out of these, autologout should NOT be set
421 * for any psudo-terminals (this catches most window systems) and not for
422 * any terminal running X windows.
424 * At Ohio State, we have had problems with a user having his X session
425 * drop out from under him (on a Sun) because the shell in his master
426 * xterm timed out and exited.
428 * Really, this should be done with a program external to the shell, that
429 * watches for no activity (and NO running programs, such as dump) on a
430 * terminal for a long peroid of time, and then SIGHUPS the shell on that
433 * bugfix by Rich Salz <rsalz@PINEAPPLE.BBN.COM>: For root rsh things
434 * allways first check to see if loginsh or really root, then do things
437 * Also by Jean-Francois Lamy <lamy%ai.toronto.edu@RELAY.CS.NET>: check the
438 * value of cp before using it! ("root can rsh too")
440 * PWP: keep the nested ifs; the order of the tests matters and a good
441 * (smart) C compiler might re-arange things wrong.
446 /* root always has a 15 minute autologout */
447 setcopy(STRautologout
, STRrootdefautologout
, VAR_READWRITE
);
450 /* users get autologout set to 0 */
451 setcopy(STRautologout
, STR0
, VAR_READWRITE
);
453 if (loginsh
|| (uid
== 0)) {
455 /* only for login shells or root and we must have a tty */
456 if ((cp2
= Strrchr(cp
, (Char
) '/')) != NULL
) {
461 if (!(((Strncmp(cp2
, STRtty
, 3) == 0) && Isalpha(cp2
[3])) ||
462 Strstr(cp
, STRptssl
) != NULL
)) {
463 if (getenv("DISPLAY") == NULL
) {
464 /* NOT on X window shells */
465 setcopy(STRautologout
, STRdefautologout
, VAR_READWRITE
);
471 #endif /* AUTOLOGOUT */
473 sigset_interrupting(SIGALRM
, queue_alrmcatch
);
475 setcopy(STRstatus
, STR0
, VAR_READWRITE
);
478 * get and set machine specific environment variables
484 * Publish the selected echo style
486 #if ECHO_STYLE != BSD_ECHO
488 # if ECHO_STYLE == NONE_ECHO
489 setcopy(STRecho_style
, STRnone
, VAR_READWRITE
);
490 # endif /* ECHO_STYLE == NONE_ECHO */
491 # if ECHO_STYLE == SYSV_ECHO
492 setcopy(STRecho_style
, STRsysv
, VAR_READWRITE
);
493 # endif /* ECHO_STYLE == SYSV_ECHO */
494 # if ECHO_STYLE == BOTH_ECHO
495 setcopy(STRecho_style
, STRboth
, VAR_READWRITE
);
496 # endif /* ECHO_STYLE == BOTH_ECHO */
498 #endif /* ECHO_STYLE != BSD_ECHO */
499 setcopy(STRecho_style
, STRbsd
, VAR_READWRITE
);
502 * increment the shell level.
506 if ((tcp
= getenv("HOME")) != NULL
)
507 cp
= quote(SAVE(tcp
));
512 fast
= 1; /* No home -> can't read scripts */
514 setv(STRhome
, cp
, VAR_READWRITE
);
516 dinit(cp
); /* dinit thinks that HOME == cwd in a login
519 * Grab other useful things from the environment. Should we grab
523 char *cln
, *cus
, *cgr
;
531 setv(STRoid
, Itoa(oid
, 0, 0), VAR_READWRITE
);
534 setv(STRuid
, Itoa(uid
, 0, 0), VAR_READWRITE
);
536 setv(STRgid
, Itoa(gid
, 0, 0), VAR_READWRITE
);
538 cln
= getenv("LOGNAME");
539 cus
= getenv("USER");
541 setv(STRuser
, quote(SAVE(cus
)), VAR_READWRITE
);
542 else if (cln
!= NULL
)
543 setv(STRuser
, quote(SAVE(cln
)), VAR_READWRITE
);
544 else if ((pw
= xgetpwuid(uid
)) == NULL
)
545 setcopy(STRuser
, str2short("unknown"), VAR_READWRITE
);
547 setcopy(STRuser
, str2short(pw
->pw_name
), VAR_READWRITE
);
549 tsetenv(STRLOGNAME
, varval(STRuser
));
551 tsetenv(STRKUSER
, varval(STRuser
));
553 cgr
= getenv("GROUP");
555 setv(STRgroup
, quote(SAVE(cgr
)), VAR_READWRITE
);
556 else if ((gr
= xgetgrgid(gid
)) == NULL
)
557 setcopy(STRgroup
, str2short("unknown"), VAR_READWRITE
);
559 setcopy(STRgroup
, str2short(gr
->gr_name
), VAR_READWRITE
);
561 tsetenv(STRKGROUP
, varval(STRgroup
));
565 * HOST may be wrong, since rexd transports the entire environment on sun
566 * 3.x Just set it again
569 char cbuff
[MAXHOSTNAMELEN
];
571 if (gethostname(cbuff
, sizeof(cbuff
)) >= 0) {
572 cbuff
[sizeof(cbuff
) - 1] = '\0'; /* just in case */
573 tsetenv(STRHOST
, str2short(cbuff
));
576 tsetenv(STRHOST
, str2short("unknown"));
582 * Try to determine the remote host we were logged in from.
585 #endif /* REMOTEHOST */
588 if ((tcp
= getenv("SYSTYPE")) == NULL
)
590 tsetenv(STRSYSTYPE
, quote(str2short(tcp
)));
594 * set editing on by default, unless running under Emacs as an inferior
596 * We try to do this intelligently. If $TERM is available, then it
597 * should determine if we should edit or not. $TERM is preserved
598 * across rlogin sessions, so we will not get confused if we rlogin
599 * under an emacs shell. Another advantage is that if we run an
600 * xterm under an emacs shell, then the $TERM will be set to
601 * xterm, so we are going to want to edit. Unfortunately emacs
602 * does not restore all the tty modes, so xterm is not very well
603 * set up. But this is not the shell's fault.
604 * Also don't edit if $TERM == wm, for when we're running under an ATK app.
605 * Finally, emacs compiled under terminfo, sets the terminal to dumb,
606 * so disable editing for that too.
608 * Unfortunately, in some cases the initial $TERM setting is "unknown",
609 * "dumb", or "network" which is then changed in the user's startup files.
610 * We fix this by setting noediting here if $TERM is unknown/dumb and
611 * if noediting is set, we switch on editing if $TERM is changed.
613 if ((tcp
= getenv("TERM")) != NULL
) {
614 setv(STRterm
, quote(SAVE(tcp
)), VAR_READWRITE
);
615 noediting
= strcmp(tcp
, "unknown") == 0 || strcmp(tcp
, "dumb") == 0 ||
616 strcmp(tcp
, "network") == 0;
617 editing
= strcmp(tcp
, "emacs") != 0 && strcmp(tcp
, "wm") != 0 &&
622 editing
= ((tcp
= getenv("EMACS")) == NULL
|| strcmp(tcp
, "t") != 0);
626 * The 'edit' variable is either set or unset. It doesn't
627 * need a value. Making it 'emacs' might be confusing.
634 * still more mutability: make the complete routine automatically add the
635 * suffix of file names...
640 * Compatibility with tcsh >= 6.12 by default
642 setNS(STRcsubstnonl
);
645 * Random default kill ring size
647 setcopy(STRkillring
, str2short("30"), VAR_READWRITE
);
650 * Re-initialize path if set in environment
652 if ((tcp
= getenv("PATH")) == NULL
) {
654 importpath(str2short(_PATH_DEFPATH
));
655 #else /* !_PATH_DEFPATH */
656 setq(STRpath
, defaultpath(), &shvhed
, VAR_READWRITE
);
657 #endif /* _PATH_DEFPATH */
659 * Export the path setting so that subsequent processes use the same path as we do.
661 exportpath(adrof(STRpath
)->vec
);
663 /* Importpath() allocates memory for the path, and the
664 * returned pointer from SAVE() was discarded, so
665 * this was a memory leak.. (sg)
667 * importpath(SAVE(tcp));
669 importpath(str2short(tcp
));
673 /* If the SHELL environment variable ends with "tcsh", set
674 * STRshell to the same path. This is to facilitate using
675 * the executable in environments where the compiled-in
676 * default isn't appropriate (sg).
681 if ((tcp
= getenv("SHELL")) != NULL
) {
682 sh_len
= strlen(tcp
);
683 if ((sh_len
>= 5 && strcmp(tcp
+ (sh_len
- 5), "/tcsh") == 0) ||
684 (!tcsh
&& sh_len
>= 4 && strcmp(tcp
+ (sh_len
- 4), "/csh") == 0))
685 setv(STRshell
, quote(SAVE(tcp
)), VAR_READWRITE
);
690 setcopy(STRshell
, STR_SHELLPATH
, VAR_READWRITE
);
693 #ifdef _OSD_POSIX /* BS2000 needs this variable set to "SHELL" */
694 if ((tcp
= getenv("PROGRAM_ENVIRONMENT")) == NULL
)
696 tsetenv(STRPROGRAM_ENVIRONMENT
, quote(str2short(tcp
)));
697 #endif /* _OSD_POSIX */
700 if ((tcp
= getenv("LS_COLORS")) != NULL
)
701 parseLS_COLORS(str2short(tcp
));
702 #endif /* COLOR_LS_F */
704 doldol
= putn((int) getpid()); /* For $$ */
709 if ((tmp
= getenv("TMP")) != NULL
) {
710 tmp
= xasprintf("%s/%s", tmp
, "sh");
717 shtemp
= Strspl(tmp2
, doldol
); /* For << */
720 #else /* !WINNT_NATIVE */
721 shtemp
= Strspl(STRtmpsh
, doldol
); /* For << */
722 #endif /* WINNT_NATIVE */
725 * Record the interrupt states from the parent process. If the parent is
726 * non-interruptible our hand must be forced or we (and our children) won't
727 * be either. Our children inherit termination from our parent. We catch it
728 * only if we are the login shell.
730 sigaction(SIGINT
, NULL
, &parintr
);
731 sigaction(SIGTERM
, NULL
, &parterm
);
735 /* Enable process migration on ourselves and our progeny */
736 (void) signal(SIGMIGRATE
, SIG_DFL
);
740 * dspkanji/dspmbyte autosetting
742 /* PATCH IDEA FROM Issei.Suzuki VERY THANKS */
743 #if defined(DSPMBYTE)
744 #if defined(NLS) && defined(LC_CTYPE)
745 if (((tcp
= setlocale(LC_CTYPE
, NULL
)) != NULL
|| (tcp
= getenv("LANG")) != NULL
) && !adrof(CHECK_MBYTEVAR
)) {
747 if ((tcp
= getenv("LANG")) != NULL
&& !adrof(CHECK_MBYTEVAR
)) {
749 autoset_dspmbyte(str2short(tcp
));
751 #if defined(WINNT_NATIVE)
752 else if (!adrof(CHECK_MBYTEVAR
))
753 nt_autoset_dspmbyte();
754 #endif /* WINNT_NATIVE */
757 fix_version(); /* publish the shell version */
759 if (argc
> 1 && strcmp(argv
[1], "--version") == 0) {
760 xprintf("%S\n", varval(STRversion
));
763 if (argc
> 1 && strcmp(argv
[1], "--help") == 0) {
764 xprintf("%S\n\n", varval(STRversion
));
765 xprintf("%s", CGETS(11, 8, HELP_STRING
));
769 * Process the arguments.
771 * Note that processing of -v/-x is actually delayed till after script
774 * We set the first character of our name to be '-' if we are a shell
775 * running interruptible commands. Many programs which examine ps'es
776 * use this to filter such shells out.
779 while (argc
> 0 && (tcp
= tempv
[0])[0] == '-' &&
780 *++tcp
!= '\0' && !batch
) {
784 case 0: /* - Interruptible, no prompt */
790 case 'b': /* -b Next arg is input file */
794 case 'c': /* -c Command input from arg */
800 it relies on a 7 bit environment (/bin/sh), so it
801 pass ascii arguments with the 8th bit set */
802 if (!strcmp(argv
[0], "sh"))
806 for (p
= tempv
[0]; *p
; ++p
)
810 arginp
= SAVE(tempv
[0]);
813 * we put the command into a variable
816 setv(STRcommand
, quote(Strsave(arginp
)), VAR_READWRITE
);
819 * * Give an error on -c arguments that end in * backslash to
820 * ensure that you don't make * nonportable csh scripts.
827 while (cp
> arginp
&& *--cp
== '\\')
829 if ((count
& 1) != 0) {
837 case 'd': /* -d Load directory stack from file */
842 case 'D': /* -D Define environment variable */
847 if (dp
= Strchr(cp
, '=')) {
852 tsetenv(cp
, STRNULL
);
854 *tcp
= '\0'; /* done with this argument */
858 case 'e': /* -e Exit on any error */
862 case 'f': /* -f Fast start */
866 case 'i': /* -i Interactive, even if !intty */
871 case 'm': /* -m read .cshrc (from su) */
875 case 'n': /* -n Don't execute */
879 case 'q': /* -q (Undoc'd) ... die on quit */
883 case 's': /* -s Read from std input */
887 case 't': /* -t Read one line from input */
893 case 'v': /* -v Echo hist expanded input */
894 nverbose
= 1; /* ... later */
897 case 'x': /* -x Echo just before execution */
898 nexececho
= 1; /* ... later */
901 case 'V': /* -V Echo hist expanded input */
902 setNS(STRverbose
); /* NOW! */
905 case 'X': /* -X Echo just before execution */
906 setNS(STRecho
); /* NOW! */
911 * This will cause children to be created using fork instead of
920 * for O/S's that don't do the argument parsing right in
921 * "#!/foo -f " scripts
925 default: /* Unknown command option */
927 stderror(ERR_TCSHUSAGE
, tcp
-1, progname
);
934 if (quitit
) /* With all due haste, for debugging */
935 (void) signal(SIGQUIT
, SIG_DFL
);
938 * Unless prevented by -, -c, -i, -s, or -t, if there are remaining
939 * arguments the first of them is the name of a shell file from which to
942 if (nofile
== 0 && argc
> 0) {
943 nofile
= xopen(tempv
[0], O_RDONLY
|O_LARGEFILE
);
945 child
= 1; /* So this ... */
946 /* ... doesn't return */
947 stderror(ERR_SYSTEM
, tempv
[0], strerror(errno
));
951 ffile
= SAVE(tempv
[0]);
953 * Replace FSHIN. Handle /dev/std{in,out,err} specially
954 * since once they are closed we cannot open them again.
955 * In that case we use our own saved descriptors
957 if ((SHIN
= dmove(nofile
, FSHIN
)) < 0)
969 stderror(ERR_SYSTEM
, tempv
[0], strerror(errno
));
972 (void) close_on_exec(SHIN
, 1);
974 /* argc not used any more */ tempv
++;
978 * Call to closem() used to be part of initdesc(). Now called below where
979 * the script name argument has become stdin. Kernel may have used a file
980 * descriptor to hold the name of the script (setuid case) and this name
981 * mustn't be lost by closing the fd too soon.
986 * Consider input a tty if it really is or we are interactive. but not for
989 if (!(intty
= isatty(SHIN
))) {
996 if (intty
|| (intact
&& isatty(SHOUT
))) {
997 if (!batch
&& (uid
!= euid
|| gid
!= egid
)) {
999 child
= 1; /* So this ... */
1000 /* ... doesn't return */
1001 stderror(ERR_SYSTEM
, progname
, strerror(errno
));
1005 isoutatty
= isatty(SHOUT
);
1006 isdiagatty
= isatty(SHDIAG
);
1008 * Decide whether we should play with signals or not. If we are explicitly
1009 * told (via -i, or -) or we are a login shell (arg0 starts with -) or the
1010 * input and output are both the ttys("csh", or "csh</dev/ttyx>/dev/ttyx")
1011 * Note that in only the login shell is it likely that parent may have set
1012 * signals to be ignored
1014 if (loginsh
|| intact
|| (intty
&& isatty(SHOUT
)))
1018 * Save the remaining arguments in argv.
1020 setq(STRargv
, blk2short(tempv
), &shvhed
, VAR_READWRITE
);
1023 * Set up the prompt.
1027 setcopy(STRprompt
, STRdeftcshprompt
, VAR_READWRITE
);
1029 setcopy(STRprompt
, STRdefcshprompt
, VAR_READWRITE
);
1030 /* that's a meta-questionmark */
1031 setcopy(STRprompt2
, STRmquestion
, VAR_READWRITE
);
1032 setcopy(STRprompt3
, STRKCORRECT
, VAR_READWRITE
);
1036 * If we are an interactive shell, then start fiddling with the signals;
1037 * this is a tricky game.
1039 shpgrp
= mygetpgrp();
1042 struct sigaction osig
;
1045 if (!quitit
) /* Wary! */
1046 (void) signal(SIGQUIT
, SIG_IGN
);
1048 sigset_interrupting(SIGINT
, queue_pintr
);
1049 (void) signal(SIGTERM
, SIG_IGN
);
1052 * No reason I can see not to save history on all these events..
1053 * Most usual occurrence is in a window system, where we're not a login
1054 * shell, but might as well be... (sg)
1055 * But there might be races when lots of shells exit together...
1056 * [this is also incompatible].
1057 * We have to be mre careful here. If the parent wants to
1058 * ignore the signals then we leave them untouched...
1059 * We also only setup the handlers for shells that are trully
1062 sigaction(SIGHUP
, NULL
, &osig
);
1063 if (loginsh
|| osig
.sa_handler
!= SIG_IGN
)
1064 /* exit processing on HUP */
1065 sigset_interrupting(SIGHUP
, queue_phup
);
1067 sigaction(SIGXCPU
, NULL
, &osig
);
1068 if (loginsh
|| osig
.sa_handler
!= SIG_IGN
)
1069 /* exit processing on XCPU */
1070 sigset_interrupting(SIGXCPU
, queue_phup
);
1073 sigaction(SIGXFSZ
, NULL
, &osig
);
1074 if (loginsh
|| osig
.sa_handler
!= SIG_IGN
)
1075 /* exit processing on XFSZ */
1076 sigset_interrupting(SIGXFSZ
, queue_phup
);
1079 if (quitit
== 0 && arginp
== 0) {
1081 (void) signal(SIGTSTP
, SIG_IGN
);
1084 (void) signal(SIGTTIN
, SIG_IGN
);
1087 (void) signal(SIGTTOU
, SIG_IGN
);
1090 * Wait till in foreground, in case someone stupidly runs csh &
1091 * dont want to try to grab away the tty.
1093 if (isatty(FSHDIAG
))
1095 else if (isatty(FSHOUT
))
1097 else if (isatty(OLDSTD
))
1103 /* NeXT 2.0 /usr/etc/rlogind, does not set our process group! */
1106 (void) setpgid(0, shpgrp
);
1107 (void) tcsetpgrp(f
, shpgrp
);
1110 #ifdef BSDJOBS /* if we have tty job control */
1111 if (grabpgrp(f
, shpgrp
) != -1) {
1113 * Thanks to Matt Day for the POSIX references, and to
1114 * Paul Close for the SGI clarification.
1116 if (setdisc(f
) != -1) {
1120 if (tcsetpgrp(f
, shpgrp
) == -1) {
1122 * On hpux 7.03 this fails with EPERM. This happens on
1123 * the 800 when opgrp != shpgrp at this point. (we were
1124 * forked from a non job control shell)
1125 * POSIX 7.2.4, says we failed because the process
1126 * group specified did not belong to a process
1127 * in the same session with the tty. So we set our
1128 * process group and try again.
1130 if (setpgid(0, shpgrp
) == -1) {
1131 xprintf("setpgid:");
1134 if (tcsetpgrp(f
, shpgrp
) == -1) {
1135 xprintf("tcsetpgrp:");
1140 * We check the process group now. If it is the same, then
1141 * we don't need to set it again. On hpux 7.0 on the 300's
1142 * if we set it again it fails with EPERM. This is the
1143 * correct behavior according to POSIX 4.3.3 if the process
1144 * was a session leader .
1146 else if (shpgrp
!= mygetpgrp()) {
1147 if(setpgid(0, shpgrp
) == -1) {
1148 xprintf("setpgid:");
1154 * But on irix 3.3 we need to set it again, even if it is
1155 * the same. We do that to tell the system that we
1156 * need BSD process group compatibility.
1159 (void) setpgid(0, shpgrp
);
1161 (void) close_on_exec(dcopy(f
, FSHTTY
), 1);
1168 xprintf(CGETS(11, 1, "Warning: no access to tty (%s).\n"),
1171 CGETS(11, 2, "Thus no job control in this shell.\n"));
1173 * Fix from:Sakari Jalovaara <sja@sirius.hut.fi> if we don't
1174 * have access to tty, disable editing too
1180 #else /* BSDJOBS */ /* don't have job control, so frotz it */
1182 #endif /* BSDJOBS */
1185 if (setintr
== 0 && parintr
.sa_handler
== SIG_DFL
)
1189 * SVR4 doesn't send a SIGCHLD when a child is stopped or continued if the
1190 * handler is installed with signal(2) or sigset(2). sigaction(2) must
1193 * David Dawes (dawes@physics.su.oz.au) Sept 1991
1195 sigset_interrupting(SIGCHLD
, queue_pchild
);
1197 if (intty
&& !arginp
)
1198 (void) ed_Setup(editing
);/* Get the tty state, and set defaults */
1199 /* Only alter the tty state if editing */
1202 * Set an exit here in case of an interrupt or error reading the shell
1207 (void)cleanup_push_mark(); /* There is no outer handler */
1208 if (setexit() != 0) /* PWP */
1213 haderr
= 0; /* In case second time through */
1214 if (!fast
&& reenter
== 0) {
1215 /* Will have varval(STRhome) here because set fast if don't */
1218 cleanup_push(&pintr_disabled
, disabled_cleanup
);
1219 setintr
= 0;/*FIXRESET:cleanup*/
1220 /* onintr in /etc/ files has no effect */
1221 parintr
.sa_handler
= SIG_IGN
;/*FIXRESET: cleanup*/
1223 #ifdef _PATH_DOTLOGIN
1225 (void) srcfile(_PATH_DOTLOGIN
, 0, 0, NULL
);
1229 #ifdef _PATH_DOTCSHRC
1230 (void) srcfile(_PATH_DOTCSHRC
, 0, 0, NULL
);
1232 if (!arginp
&& !onelflg
&& !havhash
)
1235 #ifdef _PATH_DOTLOGIN
1237 (void) srcfile(_PATH_DOTLOGIN
, 0, 0, NULL
);
1240 cleanup_until(&pintr_disabled
);
1246 (void) srccat(varval(STRhome
), STRsldotlogin
);
1248 /* upward compat. */
1249 if (!srccat(varval(STRhome
), STRsldottcshrc
))
1250 (void) srccat(varval(STRhome
), STRsldotcshrc
);
1252 if (!arginp
&& !onelflg
&& !havhash
)
1256 * Source history before .login so that it is available in .login
1261 (void) srccat(varval(STRhome
), STRsldotlogin
);
1263 if (loginsh
|| rdirs
)
1266 /* Reset interrupt flag */
1271 /* Initing AFTER .cshrc is the Right Way */
1272 if (intty
&& !arginp
) { /* PWP setup stuff */
1273 ed_Init(); /* init the new line editor */
1275 check_window_size(1); /* mung environment */
1276 #endif /* SIG_WINDOW */
1280 * Now are ready for the -v and -x flags
1288 * All the rest of the world is inside this call. The argument to process
1289 * indicates whether it should catch "error unwinds". Thus if we are a
1290 * interactive shell our call here will never return by being blown past on
1300 xprintf("logout\n");
1306 goodbye(NULL
, NULL
);
1321 if (tpgrp
> 0 && opgrp
!= shpgrp
) {
1322 (void) setpgid(0, opgrp
);
1323 (void) tcsetpgrp(FSHTTY
, opgrp
);
1324 (void) resetdisc(FSHTTY
);
1326 #endif /* BSDJOBS */
1330 importpath(Char
*cp
)
1337 for (dp
= cp
; *dp
; dp
++)
1341 * i+2 where i is the number of colons in the path. There are i+1
1342 * directories in the path plus we need room for a zero terminator.
1344 pv
= xcalloc(i
+ 2, sizeof(Char
*));
1349 if ((c
= *dp
) == PATHSEP
|| c
== 0) {
1351 pv
[i
++] = Strsave(*cp
? cp
: STRdot
);
1360 else if (*dp
== '\\')
1362 #endif /* WINNT_NATIVE */
1366 cleanup_push(pv
, blk_cleanup
);
1367 setq(STRpath
, pv
, &shvhed
, VAR_READWRITE
);
1373 * Source to the file which is the catenation of the argument names.
1376 srccat(Char
*cp
, Char
*dp
)
1378 if (cp
[0] == '/' && cp
[1] == '\0')
1379 return srcfile(short2str(dp
), (mflag
? 0 : 1), 0, NULL
);
1387 if (ep
!= cp
&& ep
[-1] == '/' && dp
[0] == '/') /* silly win95 */
1389 #endif /* WINNT_NATIVE */
1391 ep
= Strspl(cp
, dp
);
1392 cleanup_push(ep
, xfree
);
1393 ptr
= short2str(ep
);
1395 rv
= srcfile(ptr
, (mflag
? 0 : 1), 0, NULL
);
1402 * Source to a file putting the file descriptor in a safe place (> 2).
1404 #ifndef WINNT_NATIVE
1408 #endif /*WINNT_NATIVE*/
1409 srcfile(const char *f
, int onlyown
, int flag
, Char
**av
)
1413 if ((unit
= xopen(f
, O_RDONLY
|O_LARGEFILE
)) == -1)
1415 cleanup_push(&unit
, open_cleanup
);
1416 unit
= dmove(unit
, -1);
1417 cleanup_ignore(&unit
);
1418 cleanup_until(&unit
);
1420 (void) close_on_exec(unit
, 1);
1421 srcunit(unit
, onlyown
, flag
, av
);
1427 * Save the shell state, and establish new argument vector, and new input
1431 st_save(struct saved_state
*st
, int unit
, int hflg
, Char
**al
, Char
**av
)
1433 st
->insource
= insource
;
1435 /* Want to preserve the meaning of "source file >output".
1436 * Save old descriptors, move new 0,1,2 to safe places and assign
1437 * them to SH* and let process() redo 0,1,2 from them.
1439 * The macro returns true if d1 and d2 are good and they point to
1440 * different things. If you don't avoid saving duplicate
1441 * descriptors, you really limit the depth of "source" recursion
1442 * you can do because of all the open file descriptors. -IAN!
1444 #define NEED_SAVE_FD(d1,d2) \
1445 (fstat(d1, &s1) != -1 && fstat(d2, &s2) != -1 \
1446 && (s1.st_ino != s2.st_ino || s1.st_dev != s2.st_dev) )
1448 st
->OLDSTD
= st
->SHOUT
= st
->SHDIAG
= -1;/* test later to restore these */
1451 if (NEED_SAVE_FD(0,OLDSTD
)) {
1452 st
->OLDSTD
= OLDSTD
;
1453 OLDSTD
= dmove(0, -1);
1454 (void)close_on_exec(OLDSTD
, 1);
1456 if (NEED_SAVE_FD(1,SHOUT
)) {
1458 SHOUT
= dmove(1, -1);
1459 (void)close_on_exec(SHOUT
, 1);
1461 if (NEED_SAVE_FD(2,SHDIAG
)) {
1462 st
->SHDIAG
= SHDIAG
;
1463 SHDIAG
= dmove(2, -1);
1464 (void)close_on_exec(SHDIAG
, 1);
1470 st
->whyles
= whyles
;
1471 st
->gointr
= gointr
;
1472 st
->arginp
= arginp
;
1474 st
->evalvec
= evalvec
;
1475 st
->alvecp
= alvecp
;
1477 st
->onelflg
= onelflg
;
1478 st
->enterhist
= enterhist
;
1479 st
->justpr
= justpr
;
1484 st
->cantell
= cantell
;
1488 * we can now pass arguments to source.
1489 * For compatibility we do that only if arguments were really
1490 * passed, otherwise we keep the old, global $argv like before.
1492 if (av
!= NULL
&& *av
!= NULL
) {
1494 if ((vp
= adrof(STRargv
)) != NULL
&& vp
->vec
!= NULL
)
1495 st
->argv
= saveblk(vp
->vec
);
1498 setq(STRargv
, saveblk(av
), &shvhed
, VAR_READWRITE
);
1504 SHIN
= unit
; /* Do this first */
1506 /* Establish new input arena */
1509 fseekp
= feobp
= fblocks
= 0;
1515 intty
= isatty(SHIN
);
1530 * Restore the shell to a saved state
1533 st_restore(void *xst
)
1535 struct saved_state
*st
;
1541 /* Reset input arena */
1544 Char
** nfbuf
= fbuf
;
1545 int nfblocks
= fblocks
;
1549 for (i
= 0; i
< nfblocks
; i
++)
1557 insource
= st
->insource
;
1559 if (st
->OLDSTD
!= -1)
1560 xclose(OLDSTD
), OLDSTD
= st
->OLDSTD
;
1561 if (st
->SHOUT
!= -1)
1562 xclose(SHOUT
), SHOUT
= st
->SHOUT
;
1563 if (st
->SHDIAG
!= -1)
1564 xclose(SHDIAG
), SHDIAG
= st
->SHDIAG
;
1565 arginp
= st
->arginp
;
1566 onelflg
= st
->onelflg
;
1568 evalvec
= st
->evalvec
;
1569 alvecp
= st
->alvecp
;
1572 whyles
= st
->whyles
;
1573 gointr
= st
->gointr
;
1574 if (st
->HIST
!= '\0')
1576 enterhist
= st
->enterhist
;
1577 cantell
= st
->cantell
;
1578 justpr
= st
->justpr
;
1580 if (st
->argv
!= NULL
)
1581 setq(STRargv
, st
->argv
, &shvhed
, VAR_READWRITE
);
1582 else if (st
->av
!= NULL
&& *st
->av
!= NULL
&& adrof(STRargv
) != NULL
)
1587 * Source to a unit. If onlyown it must be our file or our group or
1588 * we don't chance it. This occurs on ".cshrc"s and the like.
1591 srcunit(int unit
, int onlyown
, int hflg
, Char
**av
)
1593 struct saved_state st
;
1595 st
.SHIN
= -1; /* st_restore checks this */
1603 if (fstat(unit
, &stb
) < 0) {
1609 /* Does nothing before st_save() because st.SHIN == -1 */
1610 cleanup_push(&st
, st_restore
);
1613 cleanup_push(&pintr_disabled
, disabled_cleanup
);
1616 /* Save the current state and move us to a new state */
1617 st_save(&st
, unit
, hflg
, NULL
, av
);
1620 * Now if we are allowing commands to be interrupted, we let ourselves be
1624 cleanup_until(&pintr_disabled
);
1626 cleanup_push(&pintr_disabled
, disabled_cleanup
);
1629 process(0); /* 0 -> blow away on errors */
1631 /* Restore the old state */
1638 goodbye(Char
**v
, struct command
*c
)
1649 signal(SIGQUIT
, SIG_IGN
);
1650 sigaddset(&set
, SIGQUIT
);
1651 sigprocmask(SIG_UNBLOCK
, &set
, NULL
);
1652 signal(SIGINT
, SIG_IGN
);
1653 sigaddset(&set
, SIGINT
);
1654 signal(SIGTERM
, SIG_IGN
);
1655 sigaddset(&set
, SIGTERM
);
1656 signal(SIGHUP
, SIG_IGN
);
1657 sigaddset(&set
, SIGHUP
);
1658 sigprocmask(SIG_UNBLOCK
, &set
, NULL
);
1660 setintr
= 0; /* No interrupts after "logout" */
1661 /* Trap errors inside .logout */
1662 omark
= cleanup_push_mark();
1663 if (setexit() == 0) {
1664 if (!(adrof(STRlogout
)))
1665 setcopy(STRlogout
, STRnormal
, VAR_READWRITE
);
1666 #ifdef _PATH_DOTLOGOUT
1667 (void) srcfile(_PATH_DOTLOGOUT
, 0, 0, NULL
);
1670 (void) srccat(varval(STRhome
), STRsldtlogout
);
1675 cleanup_pop_mark(omark
);
1687 * Note that if STATUS is corrupted (i.e. getn bombs) then error will exit
1688 * directly because we poke child here. Otherwise we might continue
1689 * unwarrantedly (sic).
1693 xexit(getn(varval(STRstatus
)));
1697 * in the event of a HUP we want to save the history
1703 setcopy(STRlogout
, STRhangup
, VAR_READWRITE
);
1704 #ifdef _PATH_DOTLOGOUT
1705 (void) srcfile(_PATH_DOTLOGOUT
, 0, 0, NULL
);
1708 (void) srccat(varval(STRhome
), STRsldtlogout
);
1715 * We kill the last foreground process group. It then becomes
1716 * responsible to propagate the SIGHUP to its progeny.
1719 struct process
*pp
, *np
;
1721 for (pp
= proclist
.p_next
; pp
; pp
= pp
->p_next
) {
1724 * Find if this job is in the foreground. It could be that
1725 * the process leader has exited and the foreground flag
1726 * is cleared for it.
1730 * If a process is in the foreground we try to kill
1731 * it's process group. If we succeed, then the
1732 * whole job is gone. Otherwise we keep going...
1733 * But avoid sending HUP to the shell again.
1735 if (((np
->p_flags
& PFOREGND
) != 0) && np
->p_jobid
!= shpgrp
) {
1736 np
->p_flags
&= ~PHUP
;
1737 if (killpg(np
->p_jobid
, SIGHUP
) != -1) {
1738 /* In case the job was suspended... */
1740 (void) killpg(np
->p_jobid
, SIGCONT
);
1745 while ((np
= np
->p_friends
) != pp
);
1748 #endif /* POSIXJOBS */
1753 static Char
*jobargv
[2] = {STRjobs
, 0};
1756 * Catch an interrupt, e.g. during lexical input.
1757 * If we are an interactive shell, we reset the interrupt catch
1758 * immediately. In any case we drain the shell output,
1759 * and finally go through the normal error mechanism, which
1760 * gets a chance to make the shell go away.
1762 int just_signaled
; /* bugfix by Michael Bloom (mg@ttidca.TTI.COM) */
1778 dojobs(jobargv
, NULL
);
1779 stderror(ERR_NAME
| ERR_INTR
);
1782 /* MH - handle interrupted completions specially */
1784 if (InsideCompletion
)
1785 stderror(ERR_SILENT
);
1787 /* JV - Make sure we shut off inputl */
1789 (void) Cookedmode();
1793 #ifdef HAVE_GETPWENT
1798 * If we have an active "onintr" then we search for the label. Note that if
1799 * one does "onintr -" then we shan't be interruptible so we needn't worry
1806 else if (intty
&& wantnl
) {
1809 * If we are editing a multi-line input command, and move to
1810 * the beginning of the line, we don't want to trash it when
1818 /* xputchar('\n'); *//* Some like this, others don't */
1819 (void) putraw('\r');
1820 (void) putraw('\n');
1823 stderror(ERR_SILENT
);
1827 * Process is the main driving routine for the shell.
1828 * It runs all command processing, except for those within { ... }
1829 * in expressions (which is run by a routine evalav in sh.exp.c which
1830 * is a stripped down process), and `...` evaluation which is run
1831 * also by a subset of this code in sh.glob.c in the routine backeval.
1833 * The code here is a little strange because part of it is interruptible
1834 * and hence freeing of structures appears to occur when none is necessary
1835 * if this is ignored.
1837 * Note that if catch is not set then we will unwind on any error.
1838 * If an end-of-file occurs, we return.
1844 /* PWP: This might get nuked my longjmp so don't make it a register var */
1846 volatile int didexitset
= 0;
1849 omark
= cleanup_push_mark();
1852 int hadhist
, old_pintr_disabled
;
1855 if (didexitset
== 0) {
1861 justpr
= enterhist
; /* execute if not entering history */
1867 cleanup_pop_mark(omark
);
1873 * Every error is eventually caught here or the shell dies. It is
1874 * at this point that we clean up any left-over open files, by
1875 * closing all but a fixed number of pre-defined files. Thus
1876 * routines don't have to worry about leaving files open due to
1877 * deeper errors... they will get closed here.
1890 if (intty
&& prompt
&& evalvec
== 0) {
1894 * Watch for logins/logouts. Next is scheduled commands stored
1895 * previously using "sched." Then execute periodic commands.
1896 * Following that, the prompt precmd is run.
1900 #endif /* !HAVENOUTMP */
1905 * If we are at the end of the input buffer then we are going to
1906 * read fresh stuff. Otherwise, we are rereading input and don't
1907 * need or want to prompt.
1909 if (fseekp
== feobp
&& aret
== TCSH_F_SEEK
)
1910 printprompt(0, NULL
);
1920 * Interruptible during interactive reads
1923 pintr_push_enable(&old_pintr_disabled
);
1924 hadhist
= lex(¶ml
);
1926 cleanup_until(&old_pintr_disabled
);
1927 cleanup_push(¶ml
, lex_cleanup
);
1930 * Echo not only on VERBOSE, but also with history expansion. If there
1931 * is a lexical error then we forego history echo.
1933 if ((hadhist
&& !seterr
&& intty
&& !tellwhat
&& !Expand
&& !whyles
) ||
1934 adrof(STRverbose
)) {
1935 int odidfds
= didfds
;
1943 (void) alarm(0); /* Autologout OFF */
1944 alrmcatch_disabled
= 1;
1947 * Save input text on the history list if reading in old history, or it
1948 * is from the terminal at the top level and not in a loop.
1950 * PWP: entry of items in the history list while in a while loop is done
1953 if (enterhist
|| (catch && intty
&& !whyles
&& !tellwhat
&& !arun
))
1954 savehist(¶ml
, enterhist
> 1);
1956 if (Expand
&& seterr
)
1960 * Print lexical error messages, except when sourcing history lists.
1962 if (!enterhist
&& seterr
)
1966 * If had a history command :p modifier then this is as far as we
1973 * If had a tellwhat from twenex() then do
1976 (void) tellmewhat(¶ml
, NULL
);
1984 * If we are interactive, try to continue jobs that we have stopped
1987 continue_jobs(¶ml
);
1988 #endif /* BSDJOBS */
1991 * Check to see if the user typed "rm * .o" or something
1996 * Parse the words of the input into a parse tree.
1998 t
= syntax(paraml
.next
, ¶ml
, 0);
1999 cleanup_push(t
, syntax_cleanup
);
2005 * Execute the parse tree From: Michael Schroeder
2006 * <mlschroe@immd4.informatik.uni-erlangen.de> was execute(t, tpgrp);
2008 execute(t
, (tpgrp
> 0 ? tpgrp
: -1), NULL
, NULL
, TRUE
);
2014 if (windowchg
|| (catch && intty
&& !whyles
&& !tellwhat
)) {
2015 (void) check_window_size(0); /* for window systems */
2017 #endif /* SIG_WINDOW */
2018 setcopy(STR_
, InputBuf
, VAR_READWRITE
| VAR_NOGLOB
);
2020 cleanup_until(¶ml
);
2022 cleanup_pop_mark(omark
);
2029 dosource(Char
**t
, struct command
*c
)
2037 if (*t
&& eq(*t
, STRmh
)) {
2039 stderror(ERR_NAME
| ERR_HFLAG
);
2042 else if (*t
&& eq(*t
, STRmm
)) {
2044 stderror(ERR_NAME
| ERR_MFLAG
);
2048 f
= globone(*t
++, G_ERROR
);
2049 file
= strsave(short2str(f
));
2050 cleanup_push(file
, xfree
);
2052 t
= glob_all_or_error(t
);
2053 if ((!srcfile(file
, 0, hflg
, t
)) && (!hflg
) && (!bequiet
))
2054 stderror(ERR_SYSTEM
, file
, strerror(errno
));
2055 cleanup_until(file
);
2060 * If we are a login shell, then we don't want to tell
2061 * about any mail file unless its been modified
2062 * after the time we started.
2063 * This prevents us from telling the user things he already
2064 * knows, since the login program insists on saying
2070 * This version checks if the file is a directory, and if so,
2071 * tells you the number of files in it, otherwise do the old thang.
2072 * The magic "+1" in the time calculation is to compensate for
2073 * an AFS bug where directory mtimes are set to 1 second in
2088 if (v
== NULL
|| v
->vec
== NULL
)
2093 intvl
= (cnt
&& number(*vp
)) ? (--cnt
, getn(*vp
++)) : MAILINTVL
;
2096 if (chktim
+ intvl
> t
)
2099 char *filename
= short2str(*vp
);
2100 char *mboxdir
= filename
;
2102 if (stat(filename
, &stb
) < 0)
2104 #if defined(BSDTIMES) || defined(_SEQUENT_)
2105 new = stb
.st_mtime
> time0
.tv_sec
;
2107 new = stb
.st_mtime
> seconds0
;
2109 if (S_ISDIR(stb
.st_mode
)) {
2115 tempfilename
= xasprintf("%s/new", filename
);
2117 if (stat(tempfilename
, &stc
) != -1 && S_ISDIR(stc
.st_mode
)) {
2119 * "filename/new" exists and is a directory; you are
2123 #if defined(BSDTIMES) || defined(_SEQUENT_)
2124 new = stb
.st_mtime
> time0
.tv_sec
;
2126 new = stb
.st_mtime
> seconds0
;
2128 mboxdir
= tempfilename
;
2131 if (stb
.st_mtime
<= chktim
+ 1 || (loginsh
&& !new)) {
2132 xfree(tempfilename
);
2136 mailbox
= opendir(mboxdir
);
2137 xfree(tempfilename
);
2138 if (mailbox
== NULL
)
2142 if (!readdir(mailbox
) || !readdir(mailbox
))
2145 while (readdir(mailbox
))
2152 xprintf(CGETS(11, 3, "You have %d mail messages.\n"),
2155 xprintf(CGETS(11, 4, "You have %d mail messages in %s.\n"),
2156 mailcount
, filename
);
2161 if (stb
.st_size
== 0 || stb
.st_atime
> stb
.st_mtime
||
2162 (stb
.st_atime
<= chktim
&& stb
.st_mtime
<= chktim
) ||
2165 type
= strsave(new ? CGETS(11, 6, "new ") : "");
2166 cleanup_push(type
, xfree
);
2168 xprintf(CGETS(11, 5, "You have %smail.\n"), type
);
2170 xprintf(CGETS(11, 7, "You have %smail in %s.\n"), type
, filename
);
2171 cleanup_until(type
);
2178 * Extract a home directory from the password file
2179 * The argument points to a buffer where the name of the
2180 * user whose home directory is sought is currently.
2181 * We return home directory of the user, or NULL.
2184 gethdir(const Char
*home
)
2191 if (*home
== '\0') {
2192 if ((h
= varval(STRhome
)) != STRNULL
)
2201 if ((h
= gettilde(home
)) == NULL
)
2208 * Move the initial descriptors to their eventual
2209 * resting places, closing all other units.
2217 #endif /* NLS_CATALOGS */
2218 #endif /* NLS_BUGS */
2221 didfds
= 0; /* 0, 1, 2 aren't set up */
2222 (void) close_on_exec(SHIN
= dcopy(0, FSHIN
), 1);
2223 (void) close_on_exec(SHOUT
= dcopy(1, FSHOUT
), 1);
2224 (void) close_on_exec(SHDIAG
= dcopy(2, FSHDIAG
), 1);
2225 (void) close_on_exec(OLDSTD
= dcopy(SHIN
, FOLDSTD
), 1);
2226 #ifndef CLOSE_ON_EXEC
2227 didcch
= 0; /* Havent closed for child */
2228 #endif /* CLOSE_ON_EXEC */
2229 isdiagatty
= isatty(SHDIAG
);
2230 isoutatty
= isatty(SHOUT
);
2234 #endif /* NLS_CATALOGS */
2235 #endif /* NLS_BUGS */
2247 if (loginsh
&& do_logout
) {
2248 /* this is to send hangup signal to the develcon */
2249 /* we toggle DTR. clear dtr - sleep 1 - set dtr */
2250 /* ioctl will return ENOTTY for pty's but we ignore it */
2251 /* exitstat will run after disconnect */
2252 /* we sleep for 2 seconds to let things happen in */
2253 /* .logout and rechist() */
2256 (void) ioctl(FSHTTY
, TIOCCDTR
, NULL
);
2258 (void) ioctl(FSHTTY
, TIOCSDTR
, NULL
);
2259 #endif /* TIOCCDTR */
2264 struct process
*pp
, *np
;
2266 /* Kill all processes marked for hup'ing */
2267 for (pp
= proclist
.p_next
; pp
; pp
= pp
->p_next
) {
2270 if ((np
->p_flags
& PHUP
) && np
->p_jobid
!= shpgrp
) {
2271 if (killpg(np
->p_jobid
, SIGHUP
) != -1) {
2272 /* In case the job was suspended... */
2274 (void) killpg(np
->p_jobid
, SIGCONT
);
2279 while ((np
= np
->p_friends
) != pp
);
2285 * We need to call catclose, because SVR4 leaves symlinks behind otherwise
2286 * in the catalog directories. We cannot close on a vforked() child,
2287 * because messages will stop working on the parent too.
2291 #endif /* NLS_CATALOGS */
2294 #endif /* WINNT_NATIVE */
2298 #ifndef _PATH_DEFPATH
2306 blkp
= blk
= xmalloc(sizeof(Char
*) * 10);
2310 *blkp
++ = Strsave(STRdot
);
2314 #define DIRAPPEND(a) \
2315 if (stat(ptr = a, &stb) == 0 && S_ISDIR(stb.st_mode)) \
2319 DIRAPPEND(_PATH_LOCAL
);
2323 DIRAPPEND(_PATH_USRUCB
);
2327 DIRAPPEND(_PATH_USRBSD
);
2331 DIRAPPEND(_PATH_BIN
);
2335 DIRAPPEND(_PATH_USRBIN
);
2342 *blkp
++ = Strsave(STRdot
);
2354 recdirs(NULL
, adrof(STRsavedirs
) != NULL
);
2355 rechist(NULL
, adrof(STRsavehist
) != NULL
);
2360 * Grab the tty repeatedly, and give up if we are not in the correct
2361 * tty process group.
2364 grabpgrp(int fd
, pid_t desired
)
2366 struct sigaction old
;
2370 for (i
= 0; i
< 100; i
++) {
2371 if ((pgrp
= tcgetpgrp(fd
)) == -1)
2373 if (pgrp
== desired
)
2375 (void)sigaction(SIGTTIN
, NULL
, &old
);
2376 (void)signal(SIGTTIN
, SIG_DFL
);
2377 (void)kill(0, SIGTTIN
);
2378 (void)sigaction(SIGTTIN
, &old
, NULL
);