1 /* vi: set sw=4 ts=4: */
3 * lash -- the BusyBox Lame-Ass SHell
5 * Copyright (C) 1999,2000,2001 by Lineo, inc.
6 * Written by Erik Andersen <andersen@lineo.com>, <andersee@debian.org>
8 * Based in part on ladsh.c by Michael K. Johnson and Erik W. Troan, which is
9 * under the following liberal license: "We have placed this source code in the
10 * public domain. Use it in any project, free or commercial."
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
28 /* This shell's parsing engine is officially at a dead-end.
29 * Future work shell work should be done using hush.c
32 //For debugging/development on the shell only...
43 #include <sys/ioctl.h>
51 #ifdef BB_LOCALE_SUPPORT
56 #define expand_t glob_t
59 static const int MAX_READ = 128; /* size of input buffer for `read' builtin */
60 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
63 enum redir_type { REDIRECT_INPUT, REDIRECT_OVERWRITE,
67 static const unsigned int DEFAULT_CONTEXT=0x1;
68 static const unsigned int IF_TRUE_CONTEXT=0x2;
69 static const unsigned int IF_FALSE_CONTEXT=0x4;
70 static const unsigned int THEN_EXP_CONTEXT=0x8;
71 static const unsigned int ELSE_EXP_CONTEXT=0x10;
75 struct job *head; /* head of list of running jobs */
76 struct job *fg; /* current foreground job */
80 enum redir_type type; /* type of redirection */
81 int fd; /* file descriptor being redirected */
82 char *filename; /* file to redirect fd to */
86 pid_t pid; /* 0 if exited */
87 char **argv; /* program name and arguments */
88 int num_redirects; /* elements in redirection array */
89 struct redir_struct *redirects; /* I/O redirects */
90 int is_stopped; /* is the program currently running? */
91 struct job *family; /* pointer back to the child's parent job */
95 int jobid; /* job number */
96 int num_progs; /* total number of programs in job */
97 int running_progs; /* number of programs running */
98 char *text; /* name of job */
99 char *cmdbuf; /* buffer various argv's point into */
100 pid_t pgrp; /* process group ID for the job */
101 struct child_prog *progs; /* array of programs in job */
102 struct job *next; /* to track background commands */
103 int stopped_progs; /* number of programs alive, but stopped */
104 unsigned int job_context; /* bitmask defining current context */
105 struct jobset *job_list;
108 struct built_in_command {
109 char *cmd; /* name */
110 char *descr; /* description */
111 int (*function) (struct child_prog *); /* function ptr */
116 struct close_me *next;
119 /* function prototypes for builtins */
120 static int builtin_cd(struct child_prog *cmd);
121 static int builtin_exec(struct child_prog *cmd);
122 static int builtin_exit(struct child_prog *cmd);
123 static int builtin_fg_bg(struct child_prog *cmd);
124 static int builtin_help(struct child_prog *cmd);
125 static int builtin_jobs(struct child_prog *dummy);
126 static int builtin_pwd(struct child_prog *dummy);
127 static int builtin_export(struct child_prog *cmd);
128 static int builtin_source(struct child_prog *cmd);
129 static int builtin_unset(struct child_prog *cmd);
130 static int builtin_read(struct child_prog *cmd);
133 /* function prototypes for shell stuff */
134 static void mark_open(int fd);
135 static void mark_closed(int fd);
136 static void close_all(void);
137 static void checkjobs(struct jobset *job_list);
138 static int get_command(FILE * source, char *command);
139 static int parse_command(char **command_ptr, struct job *job, int *inbg);
140 static int run_command(struct job *newjob, int inbg, int outpipe[2]);
141 static int pseudo_exec(struct child_prog *cmd) __attribute__ ((noreturn));
142 static int busy_loop(FILE * input);
145 /* Table of built-in functions (these are non-forking builtins, meaning they
146 * can change global variables in the parent shell process but they will not
147 * work with pipes and redirects; 'unset foo | whatever' will not work) */
148 static struct built_in_command bltins[] = {
149 {"bg", "Resume a job in the background", builtin_fg_bg},
150 {"cd", "Change working directory", builtin_cd},
151 {"exec", "Exec command, replacing this shell with the exec'd process", builtin_exec},
152 {"exit", "Exit from shell()", builtin_exit},
153 {"fg", "Bring job into the foreground", builtin_fg_bg},
154 {"jobs", "Lists the active jobs", builtin_jobs},
155 {"export", "Set environment variable", builtin_export},
156 {"unset", "Unset environment variable", builtin_unset},
157 {"read", "Input environment variable", builtin_read},
158 {".", "Source-in and run commands in a file", builtin_source},
159 /* to do: add ulimit */
163 /* Table of forking built-in functions (things that fork cannot change global
164 * variables in the parent process, such as the current working directory) */
165 static struct built_in_command bltins_forking[] = {
166 {"pwd", "Print current directory", builtin_pwd},
167 {"help", "List shell built-in commands", builtin_help},
172 /* Variables we export */
173 unsigned int shell_context; /* Used in cmdedit.c to reset the
174 context when someone hits ^C */
177 /* Globals that are static to this file */
178 static const char *cwd;
179 static char *local_pending_command = NULL;
180 static struct jobset job_list = { NULL, NULL };
183 static struct close_me *close_me_head;
184 static unsigned int last_jobid;
185 static int shell_terminal;
186 static pid_t shell_pgrp;
188 static char *PS2 = "> ";
192 static inline void debug_printf(const char *format, ...)
195 va_start(args, format);
196 vfprintf(stderr, format, args);
200 static inline void debug_printf(const char *format, ...) { }
204 Most builtins need access to the struct child_prog that has
205 their arguments, previously coded as cmd->progs[0]. That coding
206 can exhibit a bug, if the builtin is not the first command in
207 a pipeline: "echo foo | exec sort" will attempt to exec foo.
209 builtin previous use notes
210 ------ ----------------- ---------
212 exec cmd->progs[0] squashed bug: didn't look for applets or forking builtins
214 fg_bg cmd->progs[0], job_list->head, job_list->fg
223 I added "struct job *family;" to struct child_prog,
224 and switched API to builtin_foo(struct child_prog *child);
225 So cmd->text becomes child->family->text
226 cmd->job_context becomes child->family->job_context
227 cmd->progs[0] becomes *child
228 job_list becomes child->family->job_list
231 /* built-in 'cd <path>' handler */
232 static int builtin_cd(struct child_prog *child)
236 if (child->argv[1] == NULL)
237 newdir = getenv("HOME");
239 newdir = child->argv[1];
241 printf("cd: %s: %m\n", newdir);
244 cwd = xgetcwd((char *)cwd);
250 /* built-in 'exec' handler */
251 static int builtin_exec(struct child_prog *child)
253 if (child->argv[1] == NULL)
254 return EXIT_SUCCESS; /* Really? */
261 /* built-in 'exit' handler */
262 static int builtin_exit(struct child_prog *child)
264 if (child->argv[1] == NULL)
267 exit (atoi(child->argv[1]));
270 /* built-in 'fg' and 'bg' handler */
271 static int builtin_fg_bg(struct child_prog *child)
274 struct job *job=NULL;
276 /* If they gave us no args, assume they want the last backgrounded task */
277 if (!child->argv[1]) {
278 for (job = child->family->job_list->head; job; job = job->next) {
279 if (job->jobid == last_jobid) {
284 error_msg("%s: no current job", child->argv[0]);
288 if (sscanf(child->argv[1], "%%%d", &jobnum) != 1) {
289 error_msg("%s: bad argument '%s'", child->argv[0], child->argv[1]);
292 for (job = child->family->job_list->head; job; job = job->next) {
293 if (job->jobid == jobnum) {
298 error_msg("%s: %d: no such job", child->argv[0], jobnum);
303 if (*child->argv[0] == 'f') {
304 /* Put the job into the foreground. */
305 tcsetpgrp(shell_terminal, job->pgrp);
307 child->family->job_list->fg = job;
310 /* Restart the processes in the job */
311 for (i = 0; i < job->num_progs; i++)
312 job->progs[i].is_stopped = 0;
314 job->stopped_progs = 0;
316 if (kill(- job->pgrp, SIGCONT) < 0)
317 perror_msg("kill (SIGCONT)");
322 /* built-in 'help' handler */
323 static int builtin_help(struct child_prog *dummy)
325 struct built_in_command *x;
327 printf("\nBuilt-in commands:\n");
328 printf("-------------------\n");
329 for (x = bltins; x->cmd; x++) {
332 printf("%s\t%s\n", x->cmd, x->descr);
334 for (x = bltins_forking; x->cmd; x++) {
337 printf("%s\t%s\n", x->cmd, x->descr);
343 /* built-in 'jobs' handler */
344 static int builtin_jobs(struct child_prog *child)
349 for (job = child->family->job_list->head; job; job = job->next) {
350 if (job->running_progs == job->stopped_progs)
351 status_string = "Stopped";
353 status_string = "Running";
355 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->text);
361 /* built-in 'pwd' handler */
362 static int builtin_pwd(struct child_prog *dummy)
364 cwd = xgetcwd((char *)cwd);
371 /* built-in 'export VAR=value' handler */
372 static int builtin_export(struct child_prog *child)
375 char *v = child->argv[1];
379 for (e = environ; *e; e++) {
386 fprintf(stderr, "export: %m\n");
387 #ifdef BB_FEATURE_SH_FANCY_PROMPT
388 if (strncmp(v, "PS1=", 4)==0)
392 #ifdef BB_LOCALE_SUPPORT
393 if(strncmp(v, "LC_ALL=", 7)==0)
394 setlocale(LC_ALL, getenv("LC_ALL"));
395 if(strncmp(v, "LC_CTYPE=", 9)==0)
396 setlocale(LC_CTYPE, getenv("LC_CTYPE"));
402 /* built-in 'read VAR' handler */
403 static int builtin_read(struct child_prog *child)
405 int res = 0, len, newlen;
407 char string[MAX_READ];
409 if (child->argv[1]) {
410 /* argument (VAR) given: put "VAR=" into buffer */
411 strcpy(string, child->argv[1]);
412 len = strlen(string);
415 fgets(&string[len], sizeof(string) - len, stdin); /* read string */
416 newlen = strlen(string);
418 string[--newlen] = '\0'; /* chomp trailing newline */
420 ** string should now contain "VAR=<value>"
421 ** copy it (putenv() won't do that, so we must make sure
422 ** the string resides in a static buffer!)
425 if((s = strdup(string)))
428 fprintf(stderr, "read: %m\n");
431 fgets(string, sizeof(string), stdin);
436 /* Built-in '.' handler (read-in and execute commands from file) */
437 static int builtin_source(struct child_prog *child)
443 if (child->argv[1] == NULL)
446 input = fopen(child->argv[1], "r");
448 printf( "Couldn't open file '%s'\n", child->argv[1]);
454 /* Now run the file */
455 status = busy_loop(input);
461 /* built-in 'unset VAR' handler */
462 static int builtin_unset(struct child_prog *child)
464 if (child->argv[1] == NULL) {
465 printf( "unset: parameter required.\n");
468 unsetenv(child->argv[1]);
472 static void mark_open(int fd)
474 struct close_me *new = xmalloc(sizeof(struct close_me));
476 new->next = close_me_head;
480 static void mark_closed(int fd)
482 struct close_me *tmp;
483 if (close_me_head == NULL || close_me_head->fd != fd)
484 error_msg_and_die("corrupt close_me");
486 close_me_head = close_me_head->next;
490 static void close_all()
492 struct close_me *c, *tmp;
493 for (c=close_me_head; c; c=tmp) {
498 close_me_head = NULL;
502 /* free up all memory from a job */
503 static void free_job(struct job *cmd)
508 for (i = 0; i < cmd->num_progs; i++) {
509 free(cmd->progs[i].argv);
510 if (cmd->progs[i].redirects)
511 free(cmd->progs[i].redirects);
519 keep = cmd->job_list;
520 memset(cmd, 0, sizeof(struct job));
521 cmd->job_list = keep;
524 /* remove a job from a jobset */
525 static void remove_job(struct jobset *j_list, struct job *job)
530 if (job == j_list->head) {
531 j_list->head = job->next;
533 prevjob = j_list->head;
534 while (prevjob->next != job)
535 prevjob = prevjob->next;
536 prevjob->next = job->next;
542 /* Checks to see if any background processes have exited -- if they
543 have, figure out why and see if a job has completed */
544 static void checkjobs(struct jobset *j_list)
551 while ((childpid = waitpid(-1, &status, WNOHANG | WUNTRACED)) > 0) {
552 for (job = j_list->head; job; job = job->next) {
554 while (prognum < job->num_progs &&
555 job->progs[prognum].pid != childpid) prognum++;
556 if (prognum < job->num_progs)
560 /* This happens on backticked commands */
564 if (WIFEXITED(status) || WIFSIGNALED(status)) {
566 job->running_progs--;
567 job->progs[prognum].pid = 0;
569 if (!job->running_progs) {
570 printf(JOB_STATUS_FORMAT, job->jobid, "Done", job->text);
572 remove_job(j_list, job);
576 job->stopped_progs++;
577 job->progs[prognum].is_stopped = 1;
579 if (job->stopped_progs == job->num_progs) {
580 printf(JOB_STATUS_FORMAT, job->jobid, "Stopped",
586 if (childpid == -1 && errno != ECHILD)
587 perror_msg("waitpid");
590 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
591 * and stderr if they are redirected. */
592 static int setup_redirects(struct child_prog *prog, int squirrel[])
597 struct redir_struct *redir = prog->redirects;
599 for (i = 0; i < prog->num_redirects; i++, redir++) {
600 switch (redir->type) {
604 case REDIRECT_OVERWRITE:
605 mode = O_WRONLY | O_CREAT | O_TRUNC;
607 case REDIRECT_APPEND:
608 mode = O_WRONLY | O_CREAT | O_APPEND;
612 openfd = open(redir->filename, mode, 0666);
614 /* this could get lost if stderr has been redirected, but
615 bash and ash both lose it as well (though zsh doesn't!) */
616 perror_msg("error opening %s", redir->filename);
620 if (openfd != redir->fd) {
621 if (squirrel && redir->fd < 3) {
622 squirrel[redir->fd] = dup(redir->fd);
624 dup2(openfd, redir->fd);
632 static void restore_redirects(int squirrel[])
635 for (i=0; i<3; i++) {
638 /* No error checking. I sure wouldn't know what
639 * to do with an error if I found one! */
646 static inline void cmdedit_set_initial_prompt(void)
648 #ifndef BB_FEATURE_SH_FANCY_PROMPT
657 static inline void setup_prompt_string(char **prompt_str)
659 #ifndef BB_FEATURE_SH_FANCY_PROMPT
660 /* Set up the prompt */
661 if (shell_context == 0) {
664 PS1=xmalloc(strlen(cwd)+4);
665 sprintf(PS1, "%s %s", cwd, ( geteuid() != 0 ) ? "$ ":"# ");
671 *prompt_str = (shell_context==0)? PS1 : PS2;
675 static int get_command(FILE * source, char *command)
679 if (source == NULL) {
680 if (local_pending_command) {
681 /* a command specified (-c option): return it & mark it done */
682 strcpy(command, local_pending_command);
683 free(local_pending_command);
684 local_pending_command = NULL;
690 if (source == stdin) {
691 setup_prompt_string(&prompt_str);
693 #ifdef BB_FEATURE_COMMAND_EDITING
695 ** enable command line editing only while a command line
696 ** is actually being read; otherwise, we'll end up bequeathing
697 ** atexit() handlers and other unwanted stuff to our
698 ** child processes (rob@sysgo.de)
700 cmdedit_read_input(prompt_str, command);
704 fputs(prompt_str, stdout);
708 if (!fgets(command, BUFSIZ - 2, source)) {
718 static int expand_arguments(char *command)
722 /* get rid of the terminating \n */
725 /* Fix up escape sequences to be the Real Thing(tm) */
726 while( command && command[ix]) {
727 if (command[ix] == '\\') {
728 const char *tmp = command+ix+1;
729 command[ix] = process_escape_sequence( &tmp );
730 memmove(command+ix + 1, tmp, strlen(tmp)+1);
738 /* Return cmd->num_progs as 0 if no command is present (e.g. an empty
739 line). If a valid command is found, command_ptr is set to point to
740 the beginning of the next command (if the original command had more
741 then one job associated with it) or NULL if no more commands are
743 static int parse_command(char **command_ptr, struct job *job, int *inbg)
746 char *return_command = NULL;
747 char *src, *buf, *chptr;
751 int i, saw_quote = 0;
754 struct child_prog *prog;
756 /* skip leading white space */
757 while (**command_ptr && isspace(**command_ptr))
760 /* this handles empty lines or leading '#' characters */
761 if (!**command_ptr || (**command_ptr == '#')) {
768 job->progs = xmalloc(sizeof(*job->progs));
770 /* We set the argv elements to point inside of this string. The
771 memory is freed by free_job(). Allocate twice the original
772 length in case we need to quote every single character.
774 Getting clean memory relieves us of the task of NULL
775 terminating things and makes the rest of this look a bit
776 cleaner (though it is, admittedly, a tad less efficient) */
777 job->cmdbuf = command = xcalloc(2*strlen(*command_ptr) + 1, sizeof(char));
781 prog->num_redirects = 0;
782 prog->redirects = NULL;
783 prog->is_stopped = 0;
787 prog->argv = xmalloc(sizeof(*prog->argv) * argv_alloced);
788 prog->argv[0] = job->cmdbuf;
792 while (*src && !done) {
799 error_msg("character expected after \\");
804 /* in shell, "\'" should yield \' */
809 } else if (*src == '*' || *src == '?' || *src == '[' ||
810 *src == ']') *buf++ = '\\';
812 } else if (isspace(*src)) {
813 if (*prog->argv[argc_l] || saw_quote) {
815 /* +1 here leaves room for the NULL which ends argv */
816 if ((argc_l + 1) == argv_alloced) {
818 prog->argv = xrealloc(prog->argv,
819 sizeof(*prog->argv) *
822 prog->argv[argc_l] = buf;
833 case '#': /* comment */
840 case '>': /* redirects */
842 i = prog->num_redirects++;
843 prog->redirects = xrealloc(prog->redirects,
844 sizeof(*prog->redirects) *
847 prog->redirects[i].fd = -1;
848 if (buf != prog->argv[argc_l]) {
849 /* the stuff before this character may be the file number
851 prog->redirects[i].fd =
852 strtol(prog->argv[argc_l], &chptr, 10);
854 if (*chptr && *prog->argv[argc_l]) {
856 prog->argv[argc_l] = buf;
860 if (prog->redirects[i].fd == -1) {
862 prog->redirects[i].fd = 1;
864 prog->redirects[i].fd = 0;
869 prog->redirects[i].type =
870 REDIRECT_APPEND, src++;
872 prog->redirects[i].type = REDIRECT_OVERWRITE;
874 prog->redirects[i].type = REDIRECT_INPUT;
877 /* This isn't POSIX sh compliant. Oh well. */
879 while (isspace(*chptr))
883 error_msg("file name expected after %c", *(src-1));
889 prog->redirects[i].filename = buf;
890 while (*chptr && !isspace(*chptr))
893 src = chptr - 1; /* we src++ later */
894 prog->argv[argc_l] = ++buf;
898 /* finish this command */
899 if (*prog->argv[argc_l] || saw_quote)
902 error_msg("empty command in pipe");
907 prog->argv[argc_l] = NULL;
909 /* and start the next */
911 job->progs = xrealloc(job->progs,
912 sizeof(*job->progs) * job->num_progs);
913 prog = job->progs + (job->num_progs - 1);
914 prog->num_redirects = 0;
915 prog->redirects = NULL;
916 prog->is_stopped = 0;
921 prog->argv = xmalloc(sizeof(*prog->argv) * argv_alloced);
922 prog->argv[0] = ++buf;
925 while (*src && isspace(*src))
929 error_msg("empty command in pipe");
934 src--; /* we'll ++ it at the end of the loop */
938 case '&': /* background */
940 case ';': /* multiple commands */
942 return_command = *command_ptr + (src - *command_ptr) + 1;
948 error_msg("character expected after \\");
952 if (*src == '*' || *src == '[' || *src == ']'
953 || *src == '?') *buf++ = '\\';
962 if (*prog->argv[argc_l] || saw_quote) {
969 prog->argv[argc_l] = NULL;
971 if (!return_command) {
972 job->text = xmalloc(strlen(*command_ptr) + 1);
973 strcpy(job->text, *command_ptr);
975 /* This leaves any trailing spaces, which is a bit sloppy */
976 count = return_command - *command_ptr;
977 job->text = xmalloc(count + 1);
978 strncpy(job->text, *command_ptr, count);
979 job->text[count] = '\0';
982 *command_ptr = return_command;
987 /* Run the child_prog, no matter what kind of command it uses.
989 static int pseudo_exec(struct child_prog *child)
991 struct built_in_command *x;
992 #ifdef BB_FEATURE_SH_STANDALONE_SHELL
996 /* Check if the command matches any of the non-forking builtins.
997 * Depending on context, this might be redundant. But it's
998 * easier to waste a few CPU cycles than it is to figure out
999 * if this is one of those cases.
1001 for (x = bltins; x->cmd; x++) {
1002 if (strcmp(child->argv[0], x->cmd) == 0 ) {
1003 exit(x->function(child));
1007 /* Check if the command matches any of the forking builtins. */
1008 for (x = bltins_forking; x->cmd; x++) {
1009 if (strcmp(child->argv[0], x->cmd) == 0) {
1011 exit (x->function(child));
1014 #ifdef BB_FEATURE_SH_STANDALONE_SHELL
1015 /* Check if the command matches any busybox internal
1016 * commands ("applets") here. Following discussions from
1017 * November 2000 on busybox@opensource.lineo.com, don't use
1018 * get_last_path_component(). This way explicit (with
1019 * slashes) filenames will never be interpreted as an
1020 * applet, just like with builtins. This way the user can
1021 * override an applet with an explicit filename reference.
1022 * The only downside to this change is that an explicit
1023 * /bin/foo invocation will fork and exec /bin/foo, even if
1024 * /bin/foo is a symlink to busybox.
1026 name = child->argv[0];
1028 #ifdef BB_FEATURE_SH_APPLETS_ALWAYS_WIN
1029 /* If you enable BB_FEATURE_SH_APPLETS_ALWAYS_WIN, then
1030 * if you run /bin/cat, it will use BusyBox cat even if
1031 * /bin/cat exists on the filesystem and is _not_ busybox.
1032 * Some systems want this, others do not. Choose wisely. :-)
1034 name = get_last_path_component(name);
1038 char** argv_l=child->argv;
1040 for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++);
1042 run_applet_by_name(name, argc_l, child->argv);
1046 execvp(child->argv[0], child->argv);
1047 perror_msg_and_die("%s", child->argv[0]);
1050 static void insert_job(struct job *newjob, int inbg)
1053 struct jobset *j_list=newjob->job_list;
1055 /* find the ID for thejob to use */
1057 for (thejob = j_list->head; thejob; thejob = thejob->next)
1058 if (thejob->jobid >= newjob->jobid)
1059 newjob->jobid = thejob->jobid + 1;
1061 /* add thejob to the list of running jobs */
1062 if (!j_list->head) {
1063 thejob = j_list->head = xmalloc(sizeof(*thejob));
1065 for (thejob = j_list->head; thejob->next; thejob = thejob->next) /* nothing */;
1066 thejob->next = xmalloc(sizeof(*thejob));
1067 thejob = thejob->next;
1070 *thejob = *newjob; /* physically copy the struct job */
1071 thejob->next = NULL;
1072 thejob->running_progs = thejob->num_progs;
1073 thejob->stopped_progs = 0;
1076 /* we don't wait for background thejobs to return -- append it
1077 to the list of backgrounded thejobs and leave it alone */
1078 printf("[%d] %d\n", thejob->jobid,
1079 newjob->progs[newjob->num_progs - 1].pid);
1080 last_jobid = newjob->jobid;
1082 newjob->job_list->fg = thejob;
1084 /* move the new process group into the foreground */
1085 /* suppress messages when run from /linuxrc mag@sysgo.de */
1086 if (tcsetpgrp(shell_terminal, newjob->pgrp) && errno != ENOTTY)
1087 perror_msg("tcsetpgrp");
1091 static int run_command(struct job *newjob, int inbg, int outpipe[2])
1093 /* struct job *thejob; */
1095 int nextin, nextout;
1096 int pipefds[2]; /* pipefd[0] is for reading */
1097 struct built_in_command *x;
1098 struct child_prog *child;
1100 nextin = 0, nextout = 1;
1101 for (i = 0; i < newjob->num_progs; i++) {
1102 child = & (newjob->progs[i]);
1104 if ((i + 1) < newjob->num_progs) {
1105 if (pipe(pipefds)<0) perror_msg_and_die("pipe");
1106 nextout = pipefds[1];
1108 if (outpipe[1]!=-1) {
1109 nextout = outpipe[1];
1116 /* Check if the command matches any non-forking builtins,
1117 * but only if this is a simple command.
1118 * Non-forking builtins within pipes have to fork anyway,
1119 * and are handled in pseudo_exec. "echo foo | read bar"
1120 * is doomed to failure, and doesn't work on bash, either.
1122 if (newjob->num_progs == 1) {
1123 for (x = bltins; x->cmd; x++) {
1124 if (strcmp(child->argv[0], x->cmd) == 0 ) {
1125 int squirrel[] = {-1, -1, -1};
1127 setup_redirects(child, squirrel);
1128 rcode = x->function(child);
1129 restore_redirects(squirrel);
1135 if (!(child->pid = fork())) {
1136 /* Set the handling for job control signals back to the default. */
1137 signal(SIGINT, SIG_DFL);
1138 signal(SIGQUIT, SIG_DFL);
1139 signal(SIGTSTP, SIG_DFL);
1140 signal(SIGTTIN, SIG_DFL);
1141 signal(SIGTTOU, SIG_DFL);
1142 signal(SIGCHLD, SIG_DFL);
1146 if (outpipe[1]!=-1) {
1156 dup2(nextout, 2); /* Really? */
1161 /* explicit redirects override pipes */
1162 setup_redirects(child,NULL);
1166 if (outpipe[1]!=-1) {
1170 /* put our child in the process group whose leader is the
1171 first process in this pipe */
1172 setpgid(child->pid, newjob->progs[0].pid);
1178 /* If there isn't another process, nextin is garbage
1179 but it doesn't matter */
1180 nextin = pipefds[0];
1183 newjob->pgrp = newjob->progs[0].pid;
1185 insert_job(newjob, inbg);
1190 static int busy_loop(FILE * input)
1193 char *next_command = NULL;
1199 newjob.job_list = &job_list;
1200 newjob.job_context = DEFAULT_CONTEXT;
1202 /* save current owner of TTY so we can restore it on exit */
1203 parent_pgrp = tcgetpgrp(shell_terminal);
1205 command = (char *) xcalloc(BUFSIZ, sizeof(char));
1209 /* no job is in the foreground */
1211 /* see if any background processes have exited */
1212 checkjobs(&job_list);
1214 if (!next_command) {
1215 if (get_command(input, command))
1217 next_command = command;
1220 if (expand_arguments(next_command) == FALSE) {
1222 command = (char *) xcalloc(BUFSIZ, sizeof(char));
1223 next_command = NULL;
1227 if (!parse_command(&next_command, &newjob, &inbg) &&
1229 int pipefds[2] = {-1,-1};
1230 debug_printf( "job=%p fed to run_command by busy_loop()'\n",
1232 run_command(&newjob, inbg, pipefds);
1236 command = (char *) xcalloc(BUFSIZ, sizeof(char));
1237 next_command = NULL;
1240 /* a job is running in the foreground; wait for it */
1242 while (!job_list.fg->progs[i].pid ||
1243 job_list.fg->progs[i].is_stopped == 1) i++;
1245 if (waitpid(job_list.fg->progs[i].pid, &status, WUNTRACED)<0)
1246 perror_msg_and_die("waitpid(%d)",job_list.fg->progs[i].pid);
1248 if (WIFEXITED(status) || WIFSIGNALED(status)) {
1249 /* the child exited */
1250 job_list.fg->running_progs--;
1251 job_list.fg->progs[i].pid = 0;
1253 if (!job_list.fg->running_progs) {
1255 remove_job(&job_list, job_list.fg);
1259 /* the child was stopped */
1260 job_list.fg->stopped_progs++;
1261 job_list.fg->progs[i].is_stopped = 1;
1263 if (job_list.fg->stopped_progs == job_list.fg->running_progs) {
1264 printf("\n" JOB_STATUS_FORMAT, job_list.fg->jobid,
1265 "Stopped", job_list.fg->text);
1271 /* move the shell to the foreground */
1272 /* suppress messages when run from /linuxrc mag@sysgo.de */
1273 if (tcsetpgrp(shell_terminal, getpgrp()) && errno != ENOTTY)
1274 perror_msg("tcsetpgrp");
1280 /* return controlling TTY back to parent process group before exiting */
1281 if (tcsetpgrp(shell_terminal, parent_pgrp))
1282 perror_msg("tcsetpgrp");
1284 /* return exit status if called with "-c" */
1285 if (input == NULL && WIFEXITED(status))
1286 return WEXITSTATUS(status);
1292 #ifdef BB_FEATURE_CLEAN_UP
1293 void free_memory(void)
1298 if (local_pending_command)
1299 free(local_pending_command);
1301 if (job_list.fg && !job_list.fg->running_progs) {
1302 remove_job(&job_list, job_list.fg);
1307 /* Make sure we have a controlling tty. If we get started under a job
1308 * aware app (like bash for example), make sure we are now in charge so
1309 * we don't fight over who gets the foreground */
1310 static void setup_job_control()
1312 /* Loop until we are in the foreground. */
1313 while (tcgetpgrp (shell_terminal) != (shell_pgrp = getpgrp ()))
1314 kill (- shell_pgrp, SIGTTIN);
1316 /* Ignore interactive and job-control signals. */
1317 signal(SIGINT, SIG_IGN);
1318 signal(SIGQUIT, SIG_IGN);
1319 signal(SIGTSTP, SIG_IGN);
1320 signal(SIGTTIN, SIG_IGN);
1321 signal(SIGTTOU, SIG_IGN);
1322 signal(SIGCHLD, SIG_IGN);
1324 /* Put ourselves in our own process group. */
1325 shell_pgrp = getpid ();
1326 if (setpgid (shell_pgrp, shell_pgrp) < 0) {
1327 perror_msg_and_die("Couldn't put the shell in its own process group");
1330 /* Grab control of the terminal. */
1331 tcsetpgrp(shell_terminal, shell_pgrp);
1334 int shell_main(int argc_l, char **argv_l)
1336 int opt, interactive=FALSE;
1337 FILE *input = stdin;
1341 /* These variables need re-initializing when recursing */
1344 local_pending_command = NULL;
1345 close_me_head = NULL;
1346 job_list.head = NULL;
1349 if (argv[0] && argv[0][0] == '-') {
1351 prof_input = fopen("/etc/profile", "r");
1353 printf( "Couldn't open file '/etc/profile'\n");
1355 int tmp_fd = fileno(prof_input);
1357 /* Now run the file */
1358 busy_loop(prof_input);
1360 mark_closed(tmp_fd);
1364 while ((opt = getopt(argc_l, argv_l, "cxi")) > 0) {
1368 if (local_pending_command != 0)
1369 error_msg_and_die("multiple -c arguments");
1370 local_pending_command = xstrdup(argv[optind]);
1381 /* A shell is interactive if the `-i' flag was given, or if all of
1382 * the following conditions are met:
1384 * no arguments remaining or the -s flag given
1385 * standard input is a terminal
1386 * standard output is a terminal
1387 * Refer to Posix.2, the description of the `sh' utility. */
1388 if (argv[optind]==NULL && input==stdin &&
1389 isatty(fileno(stdin)) && isatty(fileno(stdout))) {
1392 setup_job_control();
1393 if (interactive==TRUE) {
1394 //printf( "optind=%d argv[optind]='%s'\n", optind, argv[optind]);
1395 /* Looks like they want an interactive shell */
1396 printf( "\n\n" BB_BANNER " Built-in shell (lash)\n");
1397 printf( "Enter 'help' for a list of built-in commands.\n\n");
1398 } else if (local_pending_command==NULL) {
1399 //printf( "optind=%d argv[optind]='%s'\n", optind, argv[optind]);
1400 input = xfopen(argv[optind], "r");
1401 mark_open(fileno(input)); /* be lazy, never mark this closed */
1404 /* initialize the cwd -- this is never freed...*/
1409 #ifdef BB_FEATURE_CLEAN_UP
1410 atexit(free_memory);
1413 #ifdef BB_FEATURE_COMMAND_EDITING
1414 cmdedit_set_initial_prompt();
1419 return (busy_loop(input));