1999-09-09 Federico Mena Quintero <federico@redhat.com>
[midnight-commander.git] / src / subshell.c
blob6d0953ca4eb7510c0e4ee1458ade969503e8500a
1 /* {{{ Copyright notice */
3 /* Concurrent shell support for the Midnight Commander
4 Copyright (C) 1994, 1995 Dugan Porter
6 This program is free software; you can redistribute it and/or
7 modify it under the terms of Version 2 of the GNU General Public
8 License, as published by the Free Software Foundation.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 /* }}} */
22 #include <config.h>
23 #ifdef HAVE_SUBSHELL_SUPPORT
25 /* {{{ Declarations */
27 #include <stdio.h>
28 #include <stdlib.h> /* For errno, putenv, etc. */
29 #include <errno.h> /* For errno on SunOS systems */
30 #include <termios.h> /* tcgetattr(), struct termios, etc. */
31 #if (!defined(__IBMC__) && !defined(__IBMCPP__))
32 #include <sys/types.h> /* Required by unistd.h below */
33 #endif
34 #include <sys/ioctl.h> /* For ioctl() (surprise, surprise) */
35 #include <fcntl.h> /* For open(), etc. */
36 #include <string.h> /* strstr(), strcpy(), etc. */
37 #include <signal.h> /* sigaction(), sigprocmask(), etc. */
38 #ifndef SCO_FLAVOR
39 # include <sys/time.h> /* select(), gettimeofday(), etc. */
40 #endif /* SCO_FLAVOR */
41 #include <sys/stat.h> /* Required by dir.h & panel.h below */
42 #include <sys/param.h> /* Required by panel.h below */
43 #include "tty.h"
45 #ifdef HAVE_UNISTD_H
46 # include <unistd.h> /* For pipe, fork, setsid, access etc */
47 #endif
49 #ifdef HAVE_SYS_SELECT_H
50 # include <sys/select.h>
51 #endif
53 #ifdef HAVE_SYS_WAIT_H
54 # include <sys/wait.h> /* For waitpid() */
55 #endif
57 #ifndef WEXITSTATUS
58 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
59 #endif
61 #ifndef WIFEXITED
62 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
63 #endif
65 #ifdef HAVE_GRANTPT
66 # include <stropts.h> /* For I_PUSH */
67 #else
68 # include <grp.h> /* For the group struct & getgrnam() */
69 #endif
71 #ifdef SCO_FLAVOR
72 # include <grp.h> /* For the group struct & getgrnam() */
73 #endif /* SCO_FLAVOR */
75 #ifdef __QNX__
76 # include <unix.h> /* exec*() from <process.h> */
77 #endif
79 #include "dir.h" /* Required by panel.h below */
80 #include "util.h" /* Required by panel.h */
81 #include "panel.h" /* For WPanel and current_panel */
82 #include "dialog.h" /* For query_dialog() */
83 #include "main.h" /* For cpanel, quit & init_sigchld() */
84 #include "global.h" /* For home_dir */
85 #include "cons.saver.h" /* For handle_console(), etc. */
86 #include "key.h" /* XCTRL and ALT macros */
87 #include "subshell.h"
89 /* Local functions */
90 static int feed_subshell (int how, int fail_on_error);
91 static void synchronize (void);
92 static int pty_open_master (char *pty_name);
93 static int pty_open_slave (const char *pty_name);
95 /* }}} */
96 /* {{{ Definitions */
98 #ifndef STDIN_FILENO
99 # define STDIN_FILENO 0
100 #endif
102 #ifndef STDOUT_FILENO
103 # define STDOUT_FILENO 1
104 #endif
106 #ifndef STDERR_FILENO
107 # define STDERR_FILENO 2
108 #endif
110 /* If using a subshell for evaluating commands this is true */
111 int use_subshell =
112 #ifdef SUBSHELL_OPTIONAL
113 FALSE;
114 #else
115 TRUE;
116 #endif
118 /* File descriptor of the pseudoterminal used by the subshell */
119 int subshell_pty = 0;
121 /* If true, the child forked in init_subshell will wait in a loop to be attached by gdb */
122 int debug_subshell = 0;
124 /* The key for switching back to MC from the subshell */
125 char subshell_switch_key = XCTRL('o');
127 /* State of the subshell:
128 * INACTIVE: the default state; awaiting a command
129 * ACTIVE: remain in the shell until the user hits `subshell_switch_key'
130 * RUNNING_COMMAND: return to MC when the current command finishes */
131 enum subshell_state_enum subshell_state;
133 /* Holds the latest prompt captured from the subshell */
134 char *subshell_prompt = NULL;
136 /* Initial length of the buffer for the subshell's prompt */
137 #define INITIAL_PROMPT_SIZE 10
139 /* Used by the child process to indicate failure to start the subshell */
140 #define FORK_FAILURE 69 /* Arbitrary */
142 /* Initial length of the buffer for all I/O with the subshell */
143 #define INITIAL_PTY_BUFFER_SIZE 100 /* Arbitrary; but keep it >= 80 */
145 /* For pipes */
146 enum {READ=0, WRITE=1};
149 /* Local variables */
151 static char *pty_buffer; /* For reading/writing on the subshell's pty */
152 static int pty_buffer_size; /* The buffer grows as needed */
153 static int subshell_pipe[2]; /* To pass CWD info from the subshell to MC */
154 static pid_t subshell_pid = 1; /* The subshell's process ID */
155 static char subshell_cwd[MC_MAXPATHLEN+1]; /* One extra char for final '\n' */
157 /* Subshell type (gleaned from the SHELL environment variable, if available) */
158 static enum {BASH, TCSH, ZSH} subshell_type;
160 /* Flag to indicate whether the subshell is ready for next command */
161 static int subshell_ready;
163 /* The following two flags can be changed by the SIGCHLD handler. This is */
164 /* OK, because the `int' type is updated atomically on all known machines */
165 static volatile int subshell_alive, subshell_stopped;
167 /* We store the terminal's initial mode here so that we can configure
168 the pty similarly, and also so we can restore the real terminal to
169 sanity if we have to exit abruptly */
170 static struct termios shell_mode;
172 /* This counter indicates how many characters of prompt we have read */
173 /* FIXME: try to figure out why this had to become global */
174 static int prompt_pos;
176 /* }}} */
178 /* {{{ init_subshell */
181 * Fork the subshell, and set up many, many things.
183 * Possibly modifies the global variables:
184 * shell_mode
185 * subshell_type, subshell_alive, subshell_stopped, subshell_pid
186 * use_subshell - Is set to FALSE if we can't run the subshell
187 * quit - Can be set to SUBSHELL_EXIT by the SIGCHLD handler
190 #ifdef HAVE_GRANTPT
191 # define SYNC_PTY_SIDES
192 #else
193 # define SYNC_PTY_SIDES
194 #endif
196 #undef SYNC_PTY_SIDES
198 #ifdef SYNC_PTY_SIDES
199 /* Handler for SIGUSR1 (used below), does nothing but accept the signal */
200 static void sigusr1_handler (int sig)
203 #endif
205 void init_subshell (void)
207 /* {{{ Local variables */
209 /* This must be remembered across calls to init_subshell() */
210 static char pty_name[BUF_SMALL];
211 int pty_slave;
213 /* Braindead tcsh can't redirect output to a file descriptor? */
214 char tcsh_fifo[sizeof "/tmp/mc.pipe.1234567890"];
217 #ifdef SYNC_PTY_SIDES
218 /* Used to wait for a SIGUSR1 signal from the subprocess */
219 sigset_t sigusr1_mask, old_mask;
220 #endif
222 /* }}} */
224 if (subshell_pty == 0) /* First time through */
226 /* {{{ Find out what type of shell we have */
228 if (strstr (shell, "/zsh"))
229 subshell_type = ZSH;
230 else if (strstr (shell, "/tcsh"))
231 subshell_type = TCSH;
232 else if (strstr (shell, "/bash") || getenv ("BASH"))
233 subshell_type = BASH;
234 else
236 use_subshell = FALSE;
237 return;
240 /* }}} */
241 /* {{{ Open a pty for talking to the subshell */
243 /* FIXME: We may need to open a fresh pty each time on SVR4 */
245 subshell_pty = pty_open_master (pty_name);
246 if (subshell_pty == -1)
248 fputs (__FILE__": couldn't open master side of pty\n", stderr);
249 perror ("pty_open_master");
250 use_subshell = FALSE;
251 return;
253 pty_slave = pty_open_slave (pty_name);
254 if (pty_slave == -1)
256 fprintf (stderr, "couldn't open slave side of pty (%s)\n\r",
257 pty_name);
258 use_subshell = FALSE;
259 return;
263 /* }}} */
264 /* {{{ Initialise the pty's I/O buffer */
266 pty_buffer_size = INITIAL_PTY_BUFFER_SIZE;
267 pty_buffer = (char *) g_malloc (pty_buffer_size);
269 /* }}} */
270 /* {{{ Create a pipe for receiving the subshell's CWD */
272 if (subshell_type == TCSH)
274 g_snprintf (tcsh_fifo, sizeof (tcsh_fifo), "/tmp/mc.pipe.%d", getpid ());
275 if (mkfifo (tcsh_fifo, 0600) == -1)
277 perror (__FILE__": mkfifo");
278 use_subshell = FALSE;
279 return;
282 /* Opening the FIFO as O_RDONLY or O_WRONLY causes deadlock */
284 if ((subshell_pipe[READ] = open (tcsh_fifo, O_RDWR)) == -1 ||
285 (subshell_pipe[WRITE] = open (tcsh_fifo, O_RDWR)) == -1)
287 fprintf (stderr, _("Couldn't open named pipe %s\n"), tcsh_fifo);
288 perror (__FILE__": open");
289 use_subshell = FALSE;
290 return;
293 else /* subshell_type is BASH or ZSH */
294 if (pipe (subshell_pipe))
296 perror (__FILE__": couldn't create pipe");
297 use_subshell = FALSE;
298 return;
301 /* }}} */
304 /* {{{ Define a handler for the sigusr1 signal */
306 #ifdef SYNC_PTY_SIDES
307 sigemptyset (&sigusr1_mask);
308 sigaddset (&sigusr1_mask, SIGUSR1);
309 sigprocmask (SIG_BLOCK, &sigusr1_mask, &old_mask);
310 signal (SIGUSR1, sigusr1_handler);
311 #endif
313 /* }}} */
314 /* {{{ Fork the subshell */
316 subshell_alive = TRUE;
317 subshell_stopped = FALSE;
318 subshell_pid = fork ();
320 if (subshell_pid == -1)
322 perror (__FILE__": couldn't spawn the subshell process");
323 /* We exit here because, if the process table is full, the */
324 /* other method of running user commands won't work either */
325 exit (1);
328 /* }}} */
330 if (subshell_pid == 0) /* We are in the child process */
332 char *init_file = NULL;
334 setsid (); /* Get a fresh terminal session */
336 /* {{{ Open the slave side of the pty: again */
337 pty_slave = pty_open_slave (pty_name);
339 /* This must be done before closing the master side of the pty, */
340 /* or it will fail on certain idiotic systems, such as Solaris. */
342 /* Close master side of pty. This is important; apart from */
343 /* freeing up the descriptor for use in the subshell, it also */
344 /* means that when MC exits, the subshell will get a SIGHUP and */
345 /* exit too, because there will be no more descriptors pointing */
346 /* at the master side of the pty and so it will disappear. */
348 close (subshell_pty);
350 #ifdef SYNC_PTY_SIDES
351 /* Give our parent process (MC) the go-ahead */
352 kill (getppid (), SIGUSR1);
353 #endif
355 /* }}} */
356 /* {{{ Make sure that it has become our controlling terminal */
358 /* Redundant on Linux and probably most systems, but just in case: */
360 # ifdef TIOCSCTTY
361 ioctl (pty_slave, TIOCSCTTY, 0);
362 # endif
364 /* }}} */
365 /* {{{ Configure its terminal modes and window size */
367 /* Set up the pty with the same termios flags as our own tty, plus */
368 /* TOSTOP, which keeps background processes from writing to the pty */
370 shell_mode.c_lflag |= TOSTOP; /* So background writers get SIGTTOU */
371 if (tcsetattr (pty_slave, TCSANOW, &shell_mode))
373 perror (__FILE__": couldn't set pty terminal modes");
374 _exit (FORK_FAILURE);
377 /* Set the pty's size (80x25 by default on Linux) according to the */
378 /* size of the real terminal as calculated by ncurses, if possible */
379 # if defined TIOCSWINSZ && !defined SCO_FLAVOR
381 struct winsize tty_size;
382 tty_size.ws_row = LINES;
383 tty_size.ws_col = COLS;
384 tty_size.ws_xpixel = tty_size.ws_ypixel = 0;
386 if (ioctl (pty_slave, TIOCSWINSZ, &tty_size))
387 perror (__FILE__": couldn't set pty size");
389 # endif
391 /* }}} */
392 /* {{{ Set up the subshell's environment and init file name */
394 /* It simplifies things to change to our home directory here, */
395 /* and the user's startup file may do a `cd' command anyway */
396 chdir (home_dir); /* FIXME? What about when we re-run the subshell? */
398 switch (subshell_type)
400 case BASH:
401 init_file = ".mc/bashrc";
402 if (access (init_file, R_OK) == -1)
403 init_file = ".bashrc";
405 /* Make MC's special commands not show up in bash's history */
406 putenv ("HISTCONTROL=ignorespace");
408 /* Allow alternative readline settings for MC */
409 if (access (".mc/inputrc", R_OK) == 0)
410 putenv ("INPUTRC=.mc/inputrc");
412 break;
414 case TCSH:
415 init_file = ".mc/tcshrc";
416 if (access (init_file, R_OK) == -1)
417 init_file += 3;
418 break;
420 case ZSH:
421 break;
423 default:
424 fprintf (stderr, __FILE__": unimplemented subshell type %d\n",
425 subshell_type);
426 _exit (FORK_FAILURE);
429 /* }}} */
430 /* {{{ Attach all our standard file descriptors to the pty */
432 /* This is done just before the fork, because stderr must still */
433 /* be connected to the real tty during the above error messages; */
434 /* otherwise the user will never see them. */
436 dup2 (pty_slave, STDIN_FILENO);
437 dup2 (pty_slave, STDOUT_FILENO);
438 dup2 (pty_slave, STDERR_FILENO);
440 /* }}} */
441 /* {{{ Execute the subshell at last */
443 close (subshell_pipe[READ]);
444 close (pty_slave); /* These may be FD_CLOEXEC, but just in case... */
446 switch (subshell_type)
448 case BASH:
449 execl (shell, "bash", "-rcfile", init_file, NULL);
450 break;
452 case TCSH:
453 execl (shell, "tcsh", NULL); /* What's the -rcfile equivalent? */
454 break;
456 case ZSH:
457 /* change from "+Z" to "-Z" by Michael Bramer
458 * (Debian-mc-maintainer) <grisu@debian.org> from a patch from
459 * Radovan Garabik <garabik@center.fmph.uniba.sk>
461 execl (shell, "zsh", "-Z", NULL);
463 break;
466 /* If we get this far, everything failed miserably */
467 _exit (FORK_FAILURE);
469 /* }}} */
472 close(pty_slave);
474 #ifdef SYNC_PTY_SIDES
475 sigsuspend (&old_mask);
476 signal (SIGUSR1, SIG_DFL);
477 sigprocmask (SIG_SETMASK, &old_mask, NULL);
478 /* ...before installing our handler for SIGCHLD. */
479 #endif
481 #if 0
482 /* {{{ Install our handler for SIGCHLD */
484 init_sigchld ();
486 /* We could have received the SIGCHLD signal for the subshell
487 * before installing the init_sigchld */
488 pid = waitpid (subshell_pid, &status, WUNTRACED | WNOHANG);
489 if (pid == subshell_pid){
490 use_subshell = FALSE;
491 return;
494 /* }}} */
495 #endif
497 /* {{{ Set up `precmd' or equivalent for reading the subshell's CWD */
499 switch (subshell_type)
501 char precmd[BUF_SMALL];
503 case BASH:
504 g_snprintf (precmd, sizeof (precmd), " PROMPT_COMMAND='pwd>&%d;kill -STOP $$'\n",
505 subshell_pipe[WRITE]);
506 goto write_it;
508 case ZSH:
509 g_snprintf (precmd, sizeof (precmd), "precmd(){ pwd>&%d;kill -STOP $$ }\n",
510 subshell_pipe[WRITE]);
511 goto write_it;
513 case TCSH:
514 g_snprintf (precmd, sizeof (precmd), "alias precmd 'echo $cwd:q >>%s;kill -STOP $$'\n", tcsh_fifo);
516 write_it:
517 write (subshell_pty, precmd, strlen (precmd));
520 /* }}} */
521 /* {{{ Wait until the subshell has started up and processed the command */
523 subshell_state = RUNNING_COMMAND;
524 enable_interrupt_key ();
525 if (!feed_subshell (QUIETLY, TRUE)){
526 use_subshell = FALSE;
528 disable_interrupt_key ();
529 if (!subshell_alive)
530 use_subshell = FALSE; /* Subshell died instantly, so don't use it */
532 /* }}} */
535 /* }}} */
536 /* {{{ invoke_subshell */
538 int invoke_subshell (const char *command, int how, char **new_dir)
540 /* {{{ Fiddle with terminal modes */
542 static struct termios raw_mode = {0};
544 /* MC calls reset_shell_mode() in pre_exec() to set the real tty to its */
545 /* original settings. However, here we need to make this tty very raw, */
546 /* so that all keyboard signals, XON/XOFF, etc. will get through to the */
547 /* pty. So, instead of changing the code for execute(), pre_exec(), */
548 /* etc, we just set up the modes we need here, before each command. */
550 if (raw_mode.c_iflag == 0) /* First time: initialise `raw_mode' */
552 tcgetattr (STDOUT_FILENO, &raw_mode);
553 raw_mode.c_lflag &= ~ICANON; /* Disable line-editing chars, etc. */
554 raw_mode.c_lflag &= ~ISIG; /* Disable intr, quit & suspend chars */
555 raw_mode.c_lflag &= ~ECHO; /* Disable input echoing */
556 raw_mode.c_iflag &= ~IXON; /* Pass ^S/^Q to subshell undisturbed */
557 raw_mode.c_iflag &= ~ICRNL; /* Don't translate CRs into LFs */
558 raw_mode.c_oflag &= ~OPOST; /* Don't postprocess output */
559 raw_mode.c_cc[VTIME] = 0; /* IE: wait forever, and return as */
560 raw_mode.c_cc[VMIN] = 1; /* soon as a character is available */
563 tcsetattr (STDOUT_FILENO, TCSANOW, &raw_mode);
565 /* }}} */
567 /* Make the subshell change to MC's working directory */
568 if (new_dir)
569 do_subshell_chdir (cpanel->cwd, TRUE, 1);
571 if (command == NULL) /* The user has done "C-o" from MC */
573 if (subshell_state == INACTIVE)
575 subshell_state = ACTIVE;
576 /* FIXME: possibly take out this hack; the user can
577 re-play it by hitting C-hyphen a few times! */
578 write (subshell_pty, " \b", 2); /* Hack to make prompt reappear */
581 else /* MC has passed us a user command */
583 if (how == QUIETLY)
584 write (subshell_pty, " ", 1);
585 write (subshell_pty, command, strlen (command));
586 write (subshell_pty, "\n", 1);
587 subshell_state = RUNNING_COMMAND;
588 subshell_ready = FALSE;
591 feed_subshell (how, FALSE);
593 if (new_dir && subshell_alive && strcmp (subshell_cwd, cpanel->cwd))
594 *new_dir = subshell_cwd; /* Make MC change to the subshell's CWD */
596 /* Restart the subshell if it has died by SIGHUP, SIGQUIT, etc. */
597 while (!subshell_alive && !quit && use_subshell)
598 init_subshell ();
600 prompt_pos = 0;
602 return quit;
605 /* }}} */
606 /* {{{ read_subshell_prompt */
608 int read_subshell_prompt (int how)
610 /* {{{ Local variables */
612 int clear_now = FALSE;
613 static int prompt_size = INITIAL_PROMPT_SIZE;
614 int bytes = 0, i, rc = 0;
615 struct timeval timeleft = {0, 0};
617 fd_set tmp;
618 FD_ZERO (&tmp);
619 FD_SET (subshell_pty, &tmp);
621 /* }}} */
623 if (subshell_prompt == NULL) /* First time through */
625 subshell_prompt = (char *) g_malloc (prompt_size);
626 *subshell_prompt = '\0';
627 prompt_pos = 0;
630 while (subshell_alive &&
631 (rc = select (FD_SETSIZE, &tmp, NULL, NULL, &timeleft)))
633 /* {{{ Check for `select' errors */
635 if (rc == -1) {
636 if (errno == EINTR)
637 continue;
638 else {
639 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
640 perror ("\n"__FILE__": select (FD_SETSIZE, &tmp...)");
641 exit (1);
645 /* }}} */
647 bytes = read (subshell_pty, pty_buffer, pty_buffer_size);
648 if (how == VISIBLY)
649 write (STDOUT_FILENO, pty_buffer, bytes);
651 /* {{{ Extract the prompt from the shell output */
653 for (i=0; i<bytes; ++i)
654 if (pty_buffer[i] == '\n' || pty_buffer[i] == '\r'){
655 prompt_pos = 0;
656 clear_now = FALSE;
657 } else {
658 clear_now = TRUE;
659 if (!pty_buffer [i])
660 continue;
662 subshell_prompt[prompt_pos++] = pty_buffer[i];
663 if (prompt_pos == prompt_size)
664 subshell_prompt = (char *) g_realloc (subshell_prompt,
665 prompt_size *= 2);
668 /* Sometimes we get an empty new line and then nothing,
669 * we better just keep the old prompt instead. */
670 if (clear_now)
671 subshell_prompt[prompt_pos] = '\0';
673 /* }}} */
675 if (rc == 0 && bytes == 0)
676 return FALSE;
677 return TRUE;
680 /* }}} */
681 /* {{{ resize_subshell */
683 void resize_subshell (void)
685 #if defined TIOCSWINSZ && !defined SCO_FLAVOR
686 struct winsize tty_size;
688 tty_size.ws_row = LINES;
689 tty_size.ws_col = COLS;
690 tty_size.ws_xpixel = tty_size.ws_ypixel = 0;
692 if (ioctl (subshell_pty, TIOCSWINSZ, &tty_size))
693 perror (__FILE__": couldn't set pty size");
694 #endif
697 /* }}} */
698 /* {{{ exit_subshell */
700 int exit_subshell (void)
702 int quit = TRUE;
704 if (subshell_state != INACTIVE && subshell_alive)
705 quit = !query_dialog (_(" Warning "), _(" The shell is still active. Quit anyway? "),
706 0, 2, _("&Yes"), _("&No"));
708 #if AIX_TCSH_CODE_BELOW_IS_IT_FIXED
709 /* New Test code */
710 else
712 if (subshell_type == TCSH)
713 g_snprintf (pty_buffer, pty_buffer_size, " echo -n Jobs:>/tmp/mc.pipe.%d;jobs>/tmp/"
714 "mc.pipe.%d;kill -STOP $$\n", getpid (), getpid ());
715 else
716 g_snprintf (pty_buffer, pty_buffer_size, " echo -n Jobs:>&%d;jobs>&%d;kill -STOP $$\n",
717 subshell_pipe[WRITE], subshell_pipe[WRITE]);
718 write (subshell_pty, pty_buffer, strlen (pty_buffer));
720 #ifndef HAVE_GRANTPT /* FIXME */
721 if (subshell_type == ZSH)
722 /* Here we have to drain the shell output, because zsh does a */
723 /* tcsetattr(SHTTY, TCSADRAIN...) which will block if we don't */
724 read (subshell_pty, pty_buffer, pty_buffer_size);
725 #endif
727 /* TCSH + AIX hang here, fix this before removing the ifdef above */
728 if (read (subshell_pipe[READ], pty_buffer, pty_buffer_size) == 5)
729 quit = TRUE;
730 else
731 quit = !query_dialog (_(" Warning "), _(" There are stopped jobs.")
732 _(" Quit anyway? "), 0, 2, _("&Yes"), _("&No"));
734 synchronize ();
735 subshell_state = RUNNING_COMMAND;
736 feed_subshell (QUIETLY, FALSE); /* Drain the shell output (again) */
738 #endif
740 if (quit && subshell_type == TCSH)
742 /* We abuse of pty_buffer here, but it doesn't matter at this stage */
743 g_snprintf (pty_buffer, pty_buffer_size, "/tmp/mc.pipe.%d", getpid ());
744 if (unlink (pty_buffer) == -1)
745 perror (__FILE__": couldn't remove named pipe /tmp/mc.pipe.NNN");
748 return quit;
751 /* }}} */
753 /* {{{ do_subshell_chdir */
754 /* If it actually changed the directory it returns true */
755 void do_subshell_chdir (char *directory, int do_update, int reset_prompt)
757 char *temp;
759 if (!(subshell_state == INACTIVE && strcmp (subshell_cwd, cpanel->cwd))){
760 /* We have to repaint the subshell prompt if we read it from
761 * the main program. Please note that in the code after this
762 * if, the cd command that is sent will make the subshell
763 * repaint the prompt, so we don't have to paint it. */
764 if (do_update)
765 do_update_prompt ();
766 return;
769 /* The initial space keeps this out of the command history (in bash
770 because we set "HISTCONTROL=ignorespace") */
771 write (subshell_pty, " cd ", 4);
772 if (*directory) {
773 temp = name_quote (directory, 0);
774 write (subshell_pty, temp, strlen (temp));
775 g_free (temp);
776 } else {
777 write (subshell_pty, "/", 1);
779 write (subshell_pty, "\n", 1);
781 subshell_state = RUNNING_COMMAND;
782 feed_subshell (QUIETLY, FALSE);
784 if (subshell_alive && strcmp (subshell_cwd, cpanel->cwd) && strcmp (cpanel->cwd, "."))
785 fprintf (stderr, _("Warning: Couldn't change to %s.\n"), cpanel->cwd);
787 if (reset_prompt)
788 prompt_pos = 0;
789 update_prompt = FALSE;
790 /* Make sure that MC never stores the CWD in a silly format */
791 /* like /usr////lib/../bin, or the strcmp() above will fail */
794 /* }}} */
795 /* {{{ subshell_get_console_attributes */
797 void subshell_get_console_attributes (void)
799 /* {{{ Get our current terminal modes */
801 if (tcgetattr (STDOUT_FILENO, &shell_mode))
803 perror (__FILE__": couldn't get terminal settings");
804 use_subshell = FALSE;
805 return;
808 /* }}} */
811 /* }}} */
812 /* {{{ sigchld_handler */
814 /* Figure out whether the subshell has stopped, exited or been killed */
815 /* Possibly modifies: `subshell_alive', `subshell_stopped' and `quit' */
817 void sigchld_handler (int sig)
819 int status;
820 pid_t pid;
822 pid = waitpid (subshell_pid, &status, WUNTRACED | WNOHANG);
824 if (pid == subshell_pid) {
825 /* {{{ Figure out what has happened to the subshell */
827 # ifdef SIGTSTP
828 if (WIFSTOPPED (status))
830 if (WSTOPSIG (status) == SIGTSTP)
831 /* The user has suspended the subshell. Revive it */
832 kill (subshell_pid, SIGCONT);
833 else
834 /* The subshell has received a SIGSTOP signal */
835 subshell_stopped = TRUE;
837 else /* The subshell has either exited normally or been killed */
838 # endif
840 subshell_alive = FALSE;
841 if (WIFEXITED (status) && WEXITSTATUS (status) != FORK_FAILURE)
842 quit |= SUBSHELL_EXIT; /* Exited normally */
845 /* }}} */
848 #ifndef HAVE_X
849 #ifndef SCO_FLAVOR
850 pid = waitpid (cons_saver_pid, &status, WUNTRACED | WNOHANG);
852 if (pid == cons_saver_pid) {
853 /* {{{ Someone has stopped or killed cons.saver; restart it */
855 # ifdef SIGTSTP
856 if (WIFSTOPPED (status))
857 kill (pid, SIGCONT);
858 else
859 # endif
861 handle_console (CONSOLE_DONE);
862 handle_console (CONSOLE_INIT);
863 /* Ought to do: if (in_subshell) handle_console (CONSOLE_SAVE)
864 Can't do this without adding a new variable `in_subshell';
865 it hardly seems to be worth the trouble. */
868 /* }}} */
870 #endif /* ! SCO_FLAVOR */
871 #endif /* ! HAVE_X */
872 /* If we get here, some other child exited; ignore it */
873 # ifdef __EMX__ /* Need to report */
874 pid = wait(&status);
875 # endif
878 /* }}} */
880 /* {{{ feed_subshell */
882 /* Feed the subshell our keyboard input until it says it's finished */
884 static int feed_subshell (int how, int fail_on_error)
886 /* {{{ Local variables */
887 fd_set read_set; /* For `select' */
888 int bytes; /* For the return value from `read' */
889 int i; /* Loop counter */
891 struct timeval wtime; /* Maximum time we wait for the subshell */
892 struct timeval *wptr;
893 /* }}} */
895 /* we wait up to 10 seconds if fail_on_error */
896 wtime.tv_sec = 10;
897 wtime.tv_usec = 0;
899 for (wptr = fail_on_error ? &wtime : NULL;;)
901 if (!subshell_alive)
902 return FALSE;
904 /* {{{ Prepare the file-descriptor set and call `select' */
906 FD_ZERO (&read_set);
907 FD_SET (subshell_pty, &read_set);
908 FD_SET (subshell_pipe[READ], &read_set);
909 if (how == VISIBLY)
910 FD_SET (STDIN_FILENO, &read_set);
912 if (select (FD_SETSIZE, &read_set, NULL, NULL, wptr) == -1){
914 /* Despite using SA_RESTART, we still have to check for this */
915 if (errno == EINTR)
916 continue; /* try all over again */
917 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
918 perror ("\n"__FILE__": select (FD_SETSIZE, &read_set...)");
919 exit (1);
921 /* }}} */
923 /* From now on: block forever on the select call */
924 wptr = NULL;
926 if (FD_ISSET (subshell_pty, &read_set))
927 /* {{{ Read from the subshell, write to stdout */
929 /* This loop improves performance by reducing context switches
930 by a factor of 20 or so... unfortunately, it also hangs MC
931 randomly, because of an apparent Linux bug. Investigate. */
932 /* for (i=0; i<5; ++i) * FIXME -- experimental */
934 bytes = read (subshell_pty, pty_buffer, pty_buffer_size);
935 if (bytes == -1 && errno != EIO)
937 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
938 perror ("\n"__FILE__": read (subshell_pty...)");
939 exit (1);
941 if (bytes > 0)
942 if (how == VISIBLY)
943 write (STDOUT_FILENO, pty_buffer, bytes);
946 /* }}} */
948 else if (FD_ISSET (subshell_pipe[READ], &read_set))
949 /* {{{ Read the subshell's CWD and capture its prompt */
952 bytes = read (subshell_pipe[READ], subshell_cwd, MC_MAXPATHLEN+1);
953 if (bytes == -1)
955 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
956 perror ("\n"__FILE__": read (subshell_pipe[READ]...)");
957 exit (1);
959 if (bytes >= 1)
960 subshell_cwd[bytes-1] = 0; /* Squash the final '\n' */
962 synchronize ();
964 subshell_ready = TRUE;
965 if (subshell_state == RUNNING_COMMAND)
967 subshell_state = INACTIVE;
968 return 1;
972 /* }}} */
974 else if (FD_ISSET (STDIN_FILENO, &read_set))
975 /* {{{ Read from stdin, write to the subshell */
978 bytes = read (STDIN_FILENO, pty_buffer, pty_buffer_size);
979 if (bytes == -1)
981 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
982 perror ("\n"__FILE__": read (STDIN_FILENO, pty_buffer...)");
983 exit (1);
986 for (i=0; i<bytes; ++i)
987 if (pty_buffer[i] == subshell_switch_key)
989 write (subshell_pty, pty_buffer, i);
990 if (subshell_ready)
991 subshell_state = INACTIVE;
992 return TRUE;
995 write (subshell_pty, pty_buffer, bytes);
996 subshell_ready = FALSE;
997 } else {
998 return FALSE;
1001 /* }}} */
1005 /* }}} */
1006 /* {{{ synchronize */
1008 /* Wait until the subshell dies or stops. If it stops, make it resume. */
1009 /* Possibly modifies the globals `subshell_alive' and `subshell_stopped' */
1011 static void synchronize (void)
1013 sigset_t sigchld_mask, old_mask;
1015 sigemptyset (&sigchld_mask);
1016 sigaddset (&sigchld_mask, SIGCHLD);
1017 sigprocmask (SIG_BLOCK, &sigchld_mask, &old_mask);
1019 /* Wait until the subshell has stopped */
1020 while (subshell_alive && !subshell_stopped)
1021 sigsuspend (&old_mask);
1022 subshell_stopped = FALSE;
1023 # ifdef SIGTSTP
1024 kill (subshell_pid, SIGCONT);
1025 # endif
1027 sigprocmask (SIG_SETMASK, &old_mask, NULL);
1028 /* We can't do any better without modifying the shell(s) */
1031 /* }}} */
1032 /* {{{ pty opening functions */
1034 #ifdef SCO_FLAVOR
1036 /* {{{ SCO version of pty_open_master */
1038 static int pty_open_master (char *pty_name)
1040 int pty_master;
1041 int num;
1042 char *ptr;
1044 strcpy (pty_name, "/dev/ptyp");
1045 ptr = pty_name+9;
1046 for (num=0;;num++)
1048 g_snprintf(ptr, 9, "%d",num); /* surpriiise ... SCO lacks itoa() */
1049 /* Try to open master */
1050 if ((pty_master = open (pty_name, O_RDWR)) == -1)
1051 if (errno == ENOENT) /* Different from EIO */
1052 return -1; /* Out of pty devices */
1053 else
1054 continue; /* Try next pty device */
1055 pty_name [5] = 't'; /* Change "pty" to "tty" */
1056 if (access (pty_name, 6)){
1057 close (pty_master);
1058 pty_name [5] = 'p';
1059 continue;
1061 return pty_master;
1063 return -1; /* Ran out of pty devices */
1066 /* }}} */
1067 /* {{{ SCO version of pty_open_slave */
1069 static int pty_open_slave (const char *pty_name)
1071 int pty_slave;
1072 struct group *group_info = getgrnam ("terminal");
1074 if (group_info != NULL)
1076 /* The following two calls will only succeed if we are root */
1077 /* [Commented out while permissions problem is investigated] */
1078 /* chown (pty_name, getuid (), group_info->gr_gid); FIXME */
1079 /* chmod (pty_name, S_IRUSR | S_IWUSR | S_IWGRP); FIXME */
1081 if ((pty_slave = open (pty_name, O_RDWR)) == -1)
1082 perror ("open (pty_name, O_RDWR)");
1083 return pty_slave;
1086 /* }}} */
1088 #elif HAVE_GRANTPT
1090 /* {{{ System V version of pty_open_master */
1092 static int pty_open_master (char *pty_name)
1094 char *slave_name;
1095 int pty_master;
1098 #ifdef HAVE_GETPT
1099 /* getpt () is a GNU extension (glibc 2.1.x) */
1100 pty_master = getpt ();
1101 #else
1102 strcpy (pty_name, "/dev/ptmx");
1103 pty_master = open (pty_name, O_RDWR);
1104 #endif
1105 if (pty_master == -1
1106 || grantpt (pty_master) == -1 /* Grant access to slave */
1107 || unlockpt (pty_master) == -1 /* Clear slave's lock flag */
1108 || !(slave_name = ptsname (pty_master))) /* Get slave's name */
1110 close (pty_master);
1111 return -1;
1113 strcpy (pty_name, slave_name);
1114 return pty_master;
1117 /* }}} */
1118 /* {{{ System V version of pty_open_slave */
1120 static int pty_open_slave (const char *pty_name)
1122 int pty_slave = open (pty_name, O_RDWR);
1124 if (pty_slave == -1)
1126 perror ("open (pty_name, O_RDWR)");
1127 return -1;
1130 #if !defined(__osf__) && !defined(linux) && !defined(__linux__)
1131 #if defined (I_FIND) && defined (I_PUSH)
1132 if (!ioctl (pty_slave, I_FIND, "ptem"))
1133 if (ioctl (pty_slave, I_PUSH, "ptem") == -1)
1135 perror ("ioctl (pty_slave, I_PUSH, \"ptem\")");
1136 close (pty_slave);
1137 return -1;
1140 if (!ioctl (pty_slave, I_FIND, "ldterm"))
1141 if (ioctl (pty_slave, I_PUSH, "ldterm") == -1)
1143 perror ("ioctl (pty_slave, I_PUSH, \"ldterm\")");
1144 close (pty_slave);
1145 return -1;
1148 #if !defined(sgi) && !defined(__sgi)
1149 if (!ioctl (pty_slave, I_FIND, "ttcompat"))
1150 if (ioctl (pty_slave, I_PUSH, "ttcompat") == -1)
1152 perror ("ioctl (pty_slave, I_PUSH, \"ttcompat\")");
1153 close (pty_slave);
1154 return -1;
1156 #endif /* sgi || __sgi */
1157 #endif /* I_FIND && I_PUSH */
1158 #endif /* __osf__ || linux || __linux__ */
1160 return pty_slave;
1163 /* }}} */
1165 #else
1167 /* {{{ BSD version of pty_open_master */
1169 static int pty_open_master (char *pty_name)
1171 int pty_master;
1172 char *ptr1, *ptr2;
1174 strcpy (pty_name, "/dev/ptyXX");
1175 for (ptr1 = "pqrstuvwxyzPQRST"; *ptr1; ++ptr1)
1177 pty_name [8] = *ptr1;
1178 for (ptr2 = "0123456789abcdef"; *ptr2; ++ptr2)
1180 pty_name [9] = *ptr2;
1182 /* Try to open master */
1183 if ((pty_master = open (pty_name, O_RDWR)) == -1)
1184 if (errno == ENOENT) /* Different from EIO */
1185 return -1; /* Out of pty devices */
1186 else
1187 continue; /* Try next pty device */
1188 pty_name [5] = 't'; /* Change "pty" to "tty" */
1189 if (access (pty_name, 6)){
1190 close (pty_master);
1191 pty_name [5] = 'p';
1192 continue;
1194 return pty_master;
1197 return -1; /* Ran out of pty devices */
1200 /* }}} */
1201 /* {{{ BSD version of pty_open_slave */
1203 static int pty_open_slave (const char *pty_name)
1205 int pty_slave;
1206 struct group *group_info = getgrnam ("tty");
1208 if (group_info != NULL)
1210 /* The following two calls will only succeed if we are root */
1211 /* [Commented out while permissions problem is investigated] */
1212 /* chown (pty_name, getuid (), group_info->gr_gid); FIXME */
1213 /* chmod (pty_name, S_IRUSR | S_IWUSR | S_IWGRP); FIXME */
1215 if ((pty_slave = open (pty_name, O_RDWR)) == -1)
1216 perror ("open (pty_name, O_RDWR)");
1217 return pty_slave;
1220 /* }}} */
1222 #endif
1224 /* }}} */
1226 #endif /* HAVE_SUBSHELL_SUPPORT */
1228 /* {{{ Emacs local variables */
1231 Cause emacs to enter folding mode for this file:
1232 Local variables:
1233 end:
1236 /* }}} */