1 /* Concurrent shell support for the Midnight Commander
2 Copyright (C) 1994, 1995 Dugan Porter
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of Version 2 of the GNU General Public
6 License, as published by the Free Software Foundation.
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
13 You should have received a copy of the GNU General Public License
14 along with this program; if not, write to the Free Software
15 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 #ifdef HAVE_SUBSHELL_SUPPORT
23 # define _GNU_SOURCE 1
33 #include <sys/types.h>
34 #ifdef HAVE_SYS_IOCTL_H
35 # include <sys/ioctl.h>
43 # include <stropts.h> /* For I_PUSH */
44 #endif /* HAVE_STROPTS_H */
47 #include "tty.h" /* LINES */
48 #include "panel.h" /* current_panel */
49 #include "wtools.h" /* query_dialog() */
50 #include "main.h" /* do_update_prompt() */
51 #include "cons.saver.h" /* handle_console() */
52 #include "key.h" /* XCTRL */
56 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
60 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
63 /* tcsh closes all non-standard file descriptors, so we have to use a pipe */
64 static char tcsh_fifo
[128];
67 static void init_raw_mode (void);
68 static int feed_subshell (int how
, int fail_on_error
);
69 static void synchronize (void);
70 static int pty_open_master (char *pty_name
);
71 static int pty_open_slave (const char *pty_name
);
72 static int resize_tty (int fd
);
75 # define STDIN_FILENO 0
79 # define STDOUT_FILENO 1
83 # define STDERR_FILENO 2
86 /* If using a subshell for evaluating commands this is true */
88 #ifdef SUBSHELL_OPTIONAL
94 /* File descriptor of the pseudoterminal used by the subshell */
97 /* The key for switching back to MC from the subshell */
98 static const char subshell_switch_key
= XCTRL('o') & 255;
100 /* State of the subshell:
101 * INACTIVE: the default state; awaiting a command
102 * ACTIVE: remain in the shell until the user hits `subshell_switch_key'
103 * RUNNING_COMMAND: return to MC when the current command finishes */
104 enum subshell_state_enum subshell_state
;
106 /* Holds the latest prompt captured from the subshell */
107 char *subshell_prompt
= NULL
;
109 /* Initial length of the buffer for the subshell's prompt */
110 #define INITIAL_PROMPT_SIZE 10
112 /* Used by the child process to indicate failure to start the subshell */
113 #define FORK_FAILURE 69 /* Arbitrary */
115 /* Initial length of the buffer for all I/O with the subshell */
116 #define INITIAL_PTY_BUFFER_SIZE 100 /* Arbitrary; but keep it >= 80 */
119 enum {READ
=0, WRITE
=1};
121 static char *pty_buffer
; /* For reading/writing on the subshell's pty */
122 static int pty_buffer_size
; /* The buffer grows as needed */
123 static int subshell_pipe
[2]; /* To pass CWD info from the subshell to MC */
124 static pid_t subshell_pid
= 1; /* The subshell's process ID */
125 static char subshell_cwd
[MC_MAXPATHLEN
+1]; /* One extra char for final '\n' */
127 /* Subshell type (gleaned from the SHELL environment variable, if available) */
128 static enum {BASH
, TCSH
, ZSH
} subshell_type
;
130 /* Flag to indicate whether the subshell is ready for next command */
131 static int subshell_ready
;
133 /* The following two flags can be changed by the SIGCHLD handler. This is */
134 /* OK, because the `int' type is updated atomically on all known machines */
135 static volatile int subshell_alive
, subshell_stopped
;
137 /* We store the terminal's initial mode here so that we can configure
138 the pty similarly, and also so we can restore the real terminal to
139 sanity if we have to exit abruptly */
140 static struct termios shell_mode
;
142 /* This is a transparent mode for the terminal where MC is running on */
143 /* It is used when the shell is active, so that the control signals */
144 /* are delivered to the shell pty */
145 static struct termios raw_mode
;
147 /* This counter indicates how many characters of prompt we have read */
148 /* FIXME: try to figure out why this had to become global */
149 static int prompt_pos
;
153 * Write all data, even if the write() call is interrupted.
156 write_all (int fd
, const void *buf
, size_t count
)
161 ret
= write (fd
, buf
, count
);
163 if (errno
== EINTR
) {
166 return written
> 0 ? written
: ret
;
177 * Prepare child process to running the shell and run it.
179 * Modifies the global variables (in the child process only):
185 init_subshell_child (const char *pty_name
)
188 const char *init_file
= NULL
;
191 #endif /* HAVE_GETSID */
193 setsid (); /* Get a fresh terminal session */
195 /* Open the slave side of the pty: again */
196 pty_slave
= pty_open_slave (pty_name
);
198 /* This must be done before closing the master side of the pty, */
199 /* or it will fail on certain idiotic systems, such as Solaris. */
201 /* Close master side of pty. This is important; apart from */
202 /* freeing up the descriptor for use in the subshell, it also */
203 /* means that when MC exits, the subshell will get a SIGHUP and */
204 /* exit too, because there will be no more descriptors pointing */
205 /* at the master side of the pty and so it will disappear. */
207 close (subshell_pty
);
209 /* Make sure that it has become our controlling terminal */
211 /* Redundant on Linux and probably most systems, but just in case: */
214 ioctl (pty_slave
, TIOCSCTTY
, 0);
217 /* Configure its terminal modes and window size */
219 /* Set up the pty with the same termios flags as our own tty, plus */
220 /* TOSTOP, which keeps background processes from writing to the pty */
222 shell_mode
.c_lflag
|= TOSTOP
; /* So background writers get SIGTTOU */
223 if (tcsetattr (pty_slave
, TCSANOW
, &shell_mode
)) {
224 fprintf (stderr
, "Cannot set pty terminal modes: %s\r\n",
225 unix_error_string (errno
));
226 _exit (FORK_FAILURE
);
229 /* Set the pty's size (80x25 by default on Linux) according to the */
230 /* size of the real terminal as calculated by ncurses, if possible */
231 resize_tty (pty_slave
);
233 /* Set up the subshell's environment and init file name */
235 /* It simplifies things to change to our home directory here, */
236 /* and the user's startup file may do a `cd' command anyway */
237 chdir (home_dir
); /* FIXME? What about when we re-run the subshell? */
240 /* Set MC_SID to prevent running one mc from another */
243 char sid_str
[BUF_SMALL
];
244 g_snprintf (sid_str
, sizeof (sid_str
), "MC_SID=%ld",
246 putenv (g_strdup (sid_str
));
248 #endif /* HAVE_GETSID */
250 switch (subshell_type
) {
252 init_file
= ".mc/bashrc";
253 if (access (init_file
, R_OK
) == -1)
254 init_file
= ".bashrc";
256 /* Make MC's special commands not show up in bash's history */
257 putenv ("HISTCONTROL=ignorespace");
259 /* Allow alternative readline settings for MC */
260 if (access (".mc/inputrc", R_OK
) == 0)
261 putenv ("INPUTRC=.mc/inputrc");
265 /* TODO: Find a way to pass initfile to TCSH and ZSH */
271 fprintf (stderr
, __FILE__
": unimplemented subshell type %d\r\n",
273 _exit (FORK_FAILURE
);
276 /* Attach all our standard file descriptors to the pty */
278 /* This is done just before the fork, because stderr must still */
279 /* be connected to the real tty during the above error messages; */
280 /* otherwise the user will never see them. */
282 dup2 (pty_slave
, STDIN_FILENO
);
283 dup2 (pty_slave
, STDOUT_FILENO
);
284 dup2 (pty_slave
, STDERR_FILENO
);
286 /* Execute the subshell at last */
288 close (subshell_pipe
[READ
]);
289 close (pty_slave
); /* These may be FD_CLOEXEC, but just in case... */
291 switch (subshell_type
) {
293 execl (shell
, "bash", "-rcfile", init_file
, (char *) NULL
);
297 execl (shell
, "tcsh", (char *) NULL
);
301 /* Use -g to exclude cmds beginning with space from history
302 * and -Z to use the line editor on non-interactive term */
303 execl (shell
, "zsh", "-Z", "-g", (char *) NULL
);
308 /* If we get this far, everything failed miserably */
309 _exit (FORK_FAILURE
);
315 * Check MC_SID to prevent running one mc from another.
317 * 0 if no parent mc in our session was found,
318 * 1 if parent mc was found and the user wants to continue,
319 * 2 if parent mc was found and the user wants to quit mc.
324 pid_t my_sid
, old_sid
;
328 sid_str
= getenv ("MC_SID");
332 old_sid
= (pid_t
) strtol (sid_str
, NULL
, 0);
340 /* The parent mc is in a different session, it's OK */
341 if (old_sid
!= my_sid
)
344 r
= query_dialog (_("Warning"),
345 _("GNU Midnight Commander is already\n"
346 "running on this terminal.\n"
347 "Subshell support will be disabled."), D_ERROR
, 2,
348 _("&OK"), _("&Quit"));
355 #endif /* HAVE_GETSID */
359 * Fork the subshell, and set up many, many things.
361 * Possibly modifies the global variables:
362 * subshell_type, subshell_alive, subshell_stopped, subshell_pid
363 * use_subshell - Is set to FALSE if we can't run the subshell
364 * quit - Can be set to SUBSHELL_EXIT by the SIGCHLD handler
370 /* This must be remembered across calls to init_subshell() */
371 static char pty_name
[BUF_SMALL
];
372 char precmd
[BUF_SMALL
];
376 switch (check_sid ()) {
378 use_subshell
= FALSE
;
381 use_subshell
= FALSE
;
382 midnight_shutdown
= 1;
385 #endif /* HAVE_GETSID */
387 /* Take the current (hopefully pristine) tty mode and make */
388 /* a raw mode based on it now, before we do anything else with it */
391 if (subshell_pty
== 0) { /* First time through */
392 /* Find out what type of shell we have */
394 if (strstr (shell
, "/zsh") || getenv ("ZSH_VERSION"))
396 else if (strstr (shell
, "/tcsh"))
397 subshell_type
= TCSH
;
398 else if (strstr (shell
, "/bash") || getenv ("BASH"))
399 subshell_type
= BASH
;
401 use_subshell
= FALSE
;
405 /* Open a pty for talking to the subshell */
407 /* FIXME: We may need to open a fresh pty each time on SVR4 */
409 subshell_pty
= pty_open_master (pty_name
);
410 if (subshell_pty
== -1) {
411 fprintf (stderr
, "Cannot open master side of pty: %s\r\n",
412 unix_error_string (errno
));
413 use_subshell
= FALSE
;
416 pty_slave
= pty_open_slave (pty_name
);
417 if (pty_slave
== -1) {
418 fprintf (stderr
, "Cannot open slave side of pty %s: %s\r\n",
419 pty_name
, unix_error_string (errno
));
420 use_subshell
= FALSE
;
424 /* Initialise the pty's I/O buffer */
426 pty_buffer_size
= INITIAL_PTY_BUFFER_SIZE
;
427 pty_buffer
= g_malloc (pty_buffer_size
);
429 /* Create a pipe for receiving the subshell's CWD */
431 if (subshell_type
== TCSH
) {
432 g_snprintf (tcsh_fifo
, sizeof (tcsh_fifo
), "%s/mc.pipe.%d",
433 mc_tmpdir (), (int) getpid ());
434 if (mkfifo (tcsh_fifo
, 0600) == -1) {
435 fprintf (stderr
, "mkfifo(%s) failed: %s\r\n", tcsh_fifo
,
436 unix_error_string (errno
));
437 use_subshell
= FALSE
;
441 /* Opening the FIFO as O_RDONLY or O_WRONLY causes deadlock */
443 if ((subshell_pipe
[READ
] = open (tcsh_fifo
, O_RDWR
)) == -1
444 || (subshell_pipe
[WRITE
] =
445 open (tcsh_fifo
, O_RDWR
)) == -1) {
446 fprintf (stderr
, _("Cannot open named pipe %s\n"), tcsh_fifo
);
447 perror (__FILE__
": open");
448 use_subshell
= FALSE
;
451 } else /* subshell_type is BASH or ZSH */ if (pipe (subshell_pipe
)) {
452 perror (__FILE__
": couldn't create pipe");
453 use_subshell
= FALSE
;
458 /* Fork the subshell */
460 subshell_alive
= TRUE
;
461 subshell_stopped
= FALSE
;
462 subshell_pid
= fork ();
464 if (subshell_pid
== -1) {
465 fprintf (stderr
, "Cannot spawn the subshell process: %s\r\n",
466 unix_error_string (errno
));
467 /* We exit here because, if the process table is full, the */
468 /* other method of running user commands won't work either */
472 if (subshell_pid
== 0) { /* We are in the child process */
473 init_subshell_child (pty_name
);
476 /* pty_slave is only opened when called the first time */
477 if (pty_slave
!= -1) {
481 /* Set up `precmd' or equivalent for reading the subshell's CWD */
483 switch (subshell_type
) {
485 g_snprintf (precmd
, sizeof (precmd
),
486 " PROMPT_COMMAND='pwd>&%d;kill -STOP $$'\n",
487 subshell_pipe
[WRITE
]);
491 g_snprintf (precmd
, sizeof (precmd
),
492 " precmd(){ pwd>&%d;kill -STOP $$ }\n",
493 subshell_pipe
[WRITE
]);
497 g_snprintf (precmd
, sizeof (precmd
),
498 "set echo_style=both;"
499 "alias precmd 'echo $cwd:q >>%s;kill -STOP $$'\n",
503 write_all (subshell_pty
, precmd
, strlen (precmd
));
505 /* Wait until the subshell has started up and processed the command */
507 subshell_state
= RUNNING_COMMAND
;
508 enable_interrupt_key ();
509 if (!feed_subshell (QUIETLY
, TRUE
)) {
510 use_subshell
= FALSE
;
512 disable_interrupt_key ();
514 use_subshell
= FALSE
; /* Subshell died instantly, so don't use it */
518 static void init_raw_mode ()
520 static int initialized
= 0;
522 /* MC calls reset_shell_mode() in pre_exec() to set the real tty to its */
523 /* original settings. However, here we need to make this tty very raw, */
524 /* so that all keyboard signals, XON/XOFF, etc. will get through to the */
525 /* pty. So, instead of changing the code for execute(), pre_exec(), */
526 /* etc, we just set up the modes we need here, before each command. */
528 if (initialized
== 0) /* First time: initialise `raw_mode' */
530 tcgetattr (STDOUT_FILENO
, &raw_mode
);
531 raw_mode
.c_lflag
&= ~ICANON
; /* Disable line-editing chars, etc. */
532 raw_mode
.c_lflag
&= ~ISIG
; /* Disable intr, quit & suspend chars */
533 raw_mode
.c_lflag
&= ~ECHO
; /* Disable input echoing */
534 raw_mode
.c_iflag
&= ~IXON
; /* Pass ^S/^Q to subshell undisturbed */
535 raw_mode
.c_iflag
&= ~ICRNL
; /* Don't translate CRs into LFs */
536 raw_mode
.c_oflag
&= ~OPOST
; /* Don't postprocess output */
537 raw_mode
.c_cc
[VTIME
] = 0; /* IE: wait forever, and return as */
538 raw_mode
.c_cc
[VMIN
] = 1; /* soon as a character is available */
544 int invoke_subshell (const char *command
, int how
, char **new_dir
)
546 /* Make the MC terminal transparent */
547 tcsetattr (STDOUT_FILENO
, TCSANOW
, &raw_mode
);
549 /* Make the subshell change to MC's working directory */
551 do_subshell_chdir (current_panel
->cwd
, TRUE
, 1);
553 if (command
== NULL
) /* The user has done "C-o" from MC */
555 if (subshell_state
== INACTIVE
)
557 subshell_state
= ACTIVE
;
558 /* FIXME: possibly take out this hack; the user can
559 re-play it by hitting C-hyphen a few times! */
560 write_all (subshell_pty
, " \b", 2); /* Hack to make prompt reappear */
563 else /* MC has passed us a user command */
566 write_all (subshell_pty
, " ", 1);
567 /* FIXME: if command is long (>8KB ?) we go comma */
568 write_all (subshell_pty
, command
, strlen (command
));
569 write_all (subshell_pty
, "\n", 1);
570 subshell_state
= RUNNING_COMMAND
;
571 subshell_ready
= FALSE
;
574 feed_subshell (how
, FALSE
);
576 if (new_dir
&& subshell_alive
&& strcmp (subshell_cwd
, current_panel
->cwd
))
577 *new_dir
= subshell_cwd
; /* Make MC change to the subshell's CWD */
579 /* Restart the subshell if it has died by SIGHUP, SIGQUIT, etc. */
580 while (!subshell_alive
&& !quit
&& use_subshell
)
590 read_subshell_prompt (void)
592 static int prompt_size
= INITIAL_PROMPT_SIZE
;
593 int bytes
= 0, i
, rc
= 0;
594 struct timeval timeleft
= { 0, 0 };
598 FD_SET (subshell_pty
, &tmp
);
600 if (subshell_prompt
== NULL
) { /* First time through */
601 subshell_prompt
= g_malloc (prompt_size
);
602 *subshell_prompt
= '\0';
606 while (subshell_alive
608 select (subshell_pty
+ 1, &tmp
, NULL
, NULL
, &timeleft
))) {
609 /* Check for `select' errors */
614 fprintf (stderr
, "select (FD_SETSIZE, &tmp...): %s\r\n",
615 unix_error_string (errno
));
620 bytes
= read (subshell_pty
, pty_buffer
, pty_buffer_size
);
622 /* Extract the prompt from the shell output */
624 for (i
= 0; i
< bytes
; ++i
)
625 if (pty_buffer
[i
] == '\n' || pty_buffer
[i
] == '\r') {
631 subshell_prompt
[prompt_pos
++] = pty_buffer
[i
];
632 if (prompt_pos
== prompt_size
)
634 g_realloc (subshell_prompt
, prompt_size
*= 2);
637 subshell_prompt
[prompt_pos
] = '\0';
639 if (rc
== 0 && bytes
== 0)
644 /* Resize given terminal using TIOCSWINSZ, return ioctl() result */
645 static int resize_tty (int fd
)
647 #if defined TIOCSWINSZ
648 struct winsize tty_size
;
650 tty_size
.ws_row
= LINES
;
651 tty_size
.ws_col
= COLS
;
652 tty_size
.ws_xpixel
= tty_size
.ws_ypixel
= 0;
654 return ioctl (fd
, TIOCSWINSZ
, &tty_size
);
660 /* Resize subshell_pty */
661 void resize_subshell (void)
663 resize_tty (subshell_pty
);
671 if (subshell_state
!= INACTIVE
&& subshell_alive
)
673 !query_dialog (_("Warning"),
674 _(" The shell is still active. Quit anyway? "),
675 0, 2, _("&Yes"), _("&No"));
678 if (subshell_type
== TCSH
) {
679 if (unlink (tcsh_fifo
) == -1)
680 fprintf (stderr
, "Cannot remove named pipe %s: %s\r\n",
681 tcsh_fifo
, unix_error_string (errno
));
684 g_free (subshell_prompt
);
686 subshell_prompt
= NULL
;
695 * Carefully quote directory name to allow entering any directory safely,
696 * no matter what weird characters it may contain in its name.
697 * NOTE: Treat directory name an untrusted data, don't allow it to cause
698 * executing any commands in the shell. Escape all control characters.
699 * Use following technique:
701 * for bash - echo with `-e', 3-digit octal numbers:
702 * cd "`echo -e '\ooo...\ooo'`"
704 * for zsh - echo with `-e', 4-digit octal numbers:
705 * cd "`echo '\oooo...\oooo'`"
707 * for tcsh - echo without `-e', 4-digit octal numbers:
708 * cd "`echo '\oooo...\oooo'`"
711 subshell_name_quote (const char *s
)
714 const char echo_cmd
[] = "\"`echo '";
715 const char echo_e_cmd
[] = "\"`echo -e '";
716 const char common_end
[] = "'`\"";
717 const char *cmd_start
;
721 * Factor 5 because we need \, 0 and 3 other digits per character
722 * in the worst case (tcsh and zsh).
724 d
= ret
= g_malloc (5 * strlen (s
) + 16);
728 /* Prevent interpreting leading `-' as a switch for `cd' */
734 /* echo in tcsh doesn't understand the "-e" option */
735 if (subshell_type
== TCSH
)
736 cmd_start
= echo_cmd
;
738 cmd_start
= echo_e_cmd
;
740 /* Copy the beginning of the command to the buffer */
741 len
= strlen (cmd_start
);
742 memcpy (d
, cmd_start
, len
);
746 * Print every character in octal format with the leading backslash.
747 * tcsh and zsh may require 4-digit octals, bash < 2.05b doesn't like them.
749 if (subshell_type
== BASH
) {
751 /* Must quote numbers, so that they are not glued to octals */
752 if (isalpha ((unsigned char) *s
)) {
753 *d
++ = (unsigned char) *s
;
755 sprintf (d
, "\\%03o", (unsigned char) *s
);
761 if (isalnum ((unsigned char) *s
)) {
762 *d
++ = (unsigned char) *s
;
764 sprintf (d
, "\\0%03o", (unsigned char) *s
);
770 memcpy (d
, common_end
, sizeof (common_end
));
776 /* If it actually changed the directory it returns true */
778 do_subshell_chdir (const char *directory
, int do_update
, int reset_prompt
)
781 (subshell_state
== INACTIVE
782 && strcmp (subshell_cwd
, current_panel
->cwd
))) {
783 /* We have to repaint the subshell prompt if we read it from
784 * the main program. Please note that in the code after this
785 * if, the cd command that is sent will make the subshell
786 * repaint the prompt, so we don't have to paint it. */
792 /* The initial space keeps this out of the command history (in bash
793 because we set "HISTCONTROL=ignorespace") */
794 write_all (subshell_pty
, " cd ", 4);
796 char *temp
= subshell_name_quote (directory
);
798 write_all (subshell_pty
, temp
, strlen (temp
));
801 /* Should not happen unless the directory name is so long
802 that we don't have memory to quote it. */
803 write_all (subshell_pty
, ".", 1);
806 write_all (subshell_pty
, "/", 1);
808 write_all (subshell_pty
, "\n", 1);
810 subshell_state
= RUNNING_COMMAND
;
811 feed_subshell (QUIETLY
, FALSE
);
813 if (subshell_alive
) {
814 int bPathNotEq
= strcmp (subshell_cwd
, current_panel
->cwd
);
816 if (bPathNotEq
&& subshell_type
== TCSH
) {
817 char rp_subshell_cwd
[PATH_MAX
];
818 char rp_current_panel_cwd
[PATH_MAX
];
820 char *p_subshell_cwd
=
821 mc_realpath (subshell_cwd
, rp_subshell_cwd
);
822 char *p_current_panel_cwd
=
823 mc_realpath (current_panel
->cwd
, rp_current_panel_cwd
);
825 if (p_subshell_cwd
== NULL
)
826 p_subshell_cwd
= subshell_cwd
;
827 if (p_current_panel_cwd
== NULL
)
828 p_current_panel_cwd
= current_panel
->cwd
;
829 bPathNotEq
= strcmp (p_subshell_cwd
, p_current_panel_cwd
);
832 if (bPathNotEq
&& strcmp (current_panel
->cwd
, ".")) {
833 char *cwd
= strip_password (g_strdup (current_panel
->cwd
), 1);
834 fprintf (stderr
, _("Warning: Cannot change to %s.\n"), cwd
);
841 update_prompt
= FALSE
;
842 /* Make sure that MC never stores the CWD in a silly format */
843 /* like /usr////lib/../bin, or the strcmp() above will fail */
848 subshell_get_console_attributes (void)
850 /* Get our current terminal modes */
852 if (tcgetattr (STDOUT_FILENO
, &shell_mode
)) {
853 fprintf (stderr
, "Cannot get terminal settings: %s\r\n",
854 unix_error_string (errno
));
855 use_subshell
= FALSE
;
861 /* Figure out whether the subshell has stopped, exited or been killed */
862 /* Possibly modifies: `subshell_alive', `subshell_stopped' and `quit' */
864 sigchld_handler (int sig
)
871 pid
= waitpid (subshell_pid
, &status
, WUNTRACED
| WNOHANG
);
873 if (pid
== subshell_pid
) {
874 /* Figure out what has happened to the subshell */
876 if (WIFSTOPPED (status
)) {
877 if (WSTOPSIG (status
) == SIGSTOP
) {
878 /* The subshell has received a SIGSTOP signal */
879 subshell_stopped
= TRUE
;
881 /* The user has suspended the subshell. Revive it */
882 kill (subshell_pid
, SIGCONT
);
885 /* The subshell has either exited normally or been killed */
886 subshell_alive
= FALSE
;
887 delete_select_channel (subshell_pty
);
888 if (WIFEXITED (status
) && WEXITSTATUS (status
) != FORK_FAILURE
)
889 quit
|= SUBSHELL_EXIT
; /* Exited normally */
893 pid
= waitpid (cons_saver_pid
, &status
, WUNTRACED
| WNOHANG
);
895 if (pid
== cons_saver_pid
) {
897 if (WIFSTOPPED (status
))
898 /* Someone has stopped cons.saver - restart it */
901 /* cons.saver has died - disable confole saving */
902 handle_console (CONSOLE_DONE
);
907 #endif /* __linux__ */
909 /* If we got here, some other child exited; ignore it */
910 #ifdef __EMX__ /* Need to report */
911 pid
= wait (&status
);
916 /* Feed the subshell our keyboard input until it says it's finished */
918 feed_subshell (int how
, int fail_on_error
)
920 fd_set read_set
; /* For `select' */
922 int bytes
; /* For the return value from `read' */
923 int i
; /* Loop counter */
925 struct timeval wtime
; /* Maximum time we wait for the subshell */
926 struct timeval
*wptr
;
928 /* we wait up to 10 seconds if fail_on_error, forever otherwise */
931 wptr
= fail_on_error
? &wtime
: NULL
;
937 /* Prepare the file-descriptor set and call `select' */
940 FD_SET (subshell_pty
, &read_set
);
941 FD_SET (subshell_pipe
[READ
], &read_set
);
942 maxfdp
= max (subshell_pty
, subshell_pipe
[READ
]);
943 if (how
== VISIBLY
) {
944 FD_SET (STDIN_FILENO
, &read_set
);
945 maxfdp
= max (maxfdp
, STDIN_FILENO
);
948 if (select (maxfdp
+ 1, &read_set
, NULL
, NULL
, wptr
) == -1) {
950 /* Despite using SA_RESTART, we still have to check for this */
952 continue; /* try all over again */
953 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
954 fprintf (stderr
, "select (FD_SETSIZE, &read_set...): %s\r\n",
955 unix_error_string (errno
));
959 if (FD_ISSET (subshell_pty
, &read_set
))
960 /* Read from the subshell, write to stdout */
962 /* This loop improves performance by reducing context switches
963 by a factor of 20 or so... unfortunately, it also hangs MC
964 randomly, because of an apparent Linux bug. Investigate. */
965 /* for (i=0; i<5; ++i) * FIXME -- experimental */
967 bytes
= read (subshell_pty
, pty_buffer
, pty_buffer_size
);
969 /* The subshell has died */
970 if (bytes
== -1 && errno
== EIO
&& !subshell_alive
)
974 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
975 fprintf (stderr
, "read (subshell_pty...): %s\r\n",
976 unix_error_string (errno
));
981 write_all (STDOUT_FILENO
, pty_buffer
, bytes
);
984 else if (FD_ISSET (subshell_pipe
[READ
], &read_set
))
985 /* Read the subshell's CWD and capture its prompt */
989 read (subshell_pipe
[READ
], subshell_cwd
,
992 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
993 fprintf (stderr
, "read (subshell_pipe[READ]...): %s\r\n",
994 unix_error_string (errno
));
998 subshell_cwd
[bytes
- 1] = 0; /* Squash the final '\n' */
1002 subshell_ready
= TRUE
;
1003 if (subshell_state
== RUNNING_COMMAND
) {
1004 subshell_state
= INACTIVE
;
1009 else if (FD_ISSET (STDIN_FILENO
, &read_set
))
1010 /* Read from stdin, write to the subshell */
1012 bytes
= read (STDIN_FILENO
, pty_buffer
, pty_buffer_size
);
1014 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
1016 "read (STDIN_FILENO, pty_buffer...): %s\r\n",
1017 unix_error_string (errno
));
1021 for (i
= 0; i
< bytes
; ++i
)
1022 if (pty_buffer
[i
] == subshell_switch_key
) {
1023 write_all (subshell_pty
, pty_buffer
, i
);
1025 subshell_state
= INACTIVE
;
1029 write_all (subshell_pty
, pty_buffer
, bytes
);
1030 subshell_ready
= FALSE
;
1038 /* Wait until the subshell dies or stops. If it stops, make it resume. */
1039 /* Possibly modifies the globals `subshell_alive' and `subshell_stopped' */
1040 static void synchronize (void)
1042 sigset_t sigchld_mask
, old_mask
;
1044 sigemptyset (&sigchld_mask
);
1045 sigaddset (&sigchld_mask
, SIGCHLD
);
1046 sigprocmask (SIG_BLOCK
, &sigchld_mask
, &old_mask
);
1049 * SIGCHLD should not be blocked, but we unblock it just in case.
1050 * This is known to be useful for cygwin 1.3.12 and older.
1052 sigdelset (&old_mask
, SIGCHLD
);
1054 /* Wait until the subshell has stopped */
1055 while (subshell_alive
&& !subshell_stopped
)
1056 sigsuspend (&old_mask
);
1058 /* Discard all remaining data from stdin to the subshell */
1059 tcflush (subshell_pty
, TCOFLUSH
);
1061 subshell_stopped
= FALSE
;
1062 kill (subshell_pid
, SIGCONT
);
1064 sigprocmask (SIG_SETMASK
, &old_mask
, NULL
);
1065 /* We can't do any better without modifying the shell(s) */
1068 /* pty opening functions */
1072 /* System V version of pty_open_master */
1074 static int pty_open_master (char *pty_name
)
1079 #ifdef HAVE_POSIX_OPENPT
1080 pty_master
= posix_openpt(O_RDWR
);
1082 /* getpt () is a GNU extension (glibc 2.1.x) */
1083 pty_master
= getpt ();
1085 strcpy (pty_name
, "/dev/ptc");
1086 pty_master
= open (pty_name
, O_RDWR
);
1088 strcpy (pty_name
, "/dev/ptmx");
1089 pty_master
= open (pty_name
, O_RDWR
);
1092 if (pty_master
== -1)
1095 if (grantpt (pty_master
) == -1 /* Grant access to slave */
1096 || unlockpt (pty_master
) == -1 /* Clear slave's lock flag */
1097 || !(slave_name
= ptsname (pty_master
))) /* Get slave's name */
1102 strcpy (pty_name
, slave_name
);
1106 /* System V version of pty_open_slave */
1108 pty_open_slave (const char *pty_name
)
1110 int pty_slave
= open (pty_name
, O_RDWR
);
1112 if (pty_slave
== -1) {
1113 fprintf (stderr
, "open (%s, O_RDWR): %s\r\n", pty_name
,
1114 unix_error_string (errno
));
1117 #if !defined(__osf__) && !defined(__linux__)
1118 #if defined (I_FIND) && defined (I_PUSH)
1119 if (!ioctl (pty_slave
, I_FIND
, "ptem"))
1120 if (ioctl (pty_slave
, I_PUSH
, "ptem") == -1) {
1121 fprintf (stderr
, "ioctl (%d, I_PUSH, \"ptem\") failed: %s\r\n",
1122 pty_slave
, unix_error_string (errno
));
1127 if (!ioctl (pty_slave
, I_FIND
, "ldterm"))
1128 if (ioctl (pty_slave
, I_PUSH
, "ldterm") == -1) {
1130 "ioctl (%d, I_PUSH, \"ldterm\") failed: %s\r\n",
1131 pty_slave
, unix_error_string (errno
));
1135 #if !defined(sgi) && !defined(__sgi)
1136 if (!ioctl (pty_slave
, I_FIND
, "ttcompat"))
1137 if (ioctl (pty_slave
, I_PUSH
, "ttcompat") == -1) {
1139 "ioctl (%d, I_PUSH, \"ttcompat\") failed: %s\r\n",
1140 pty_slave
, unix_error_string (errno
));
1144 #endif /* sgi || __sgi */
1145 #endif /* I_FIND && I_PUSH */
1146 #endif /* __osf__ || __linux__ */
1151 #else /* !HAVE_GRANTPT */
1153 /* BSD version of pty_open_master */
1154 static int pty_open_master (char *pty_name
)
1157 const char *ptr1
, *ptr2
;
1159 strcpy (pty_name
, "/dev/ptyXX");
1160 for (ptr1
= "pqrstuvwxyzPQRST"; *ptr1
; ++ptr1
)
1162 pty_name
[8] = *ptr1
;
1163 for (ptr2
= "0123456789abcdef"; *ptr2
; ++ptr2
)
1165 pty_name
[9] = *ptr2
;
1167 /* Try to open master */
1168 if ((pty_master
= open (pty_name
, O_RDWR
)) == -1) {
1169 if (errno
== ENOENT
) /* Different from EIO */
1170 return -1; /* Out of pty devices */
1172 continue; /* Try next pty device */
1174 pty_name
[5] = 't'; /* Change "pty" to "tty" */
1175 if (access (pty_name
, 6)){
1183 return -1; /* Ran out of pty devices */
1186 /* BSD version of pty_open_slave */
1188 pty_open_slave (const char *pty_name
)
1191 struct group
*group_info
= getgrnam ("tty");
1193 if (group_info
!= NULL
) {
1194 /* The following two calls will only succeed if we are root */
1195 /* [Commented out while permissions problem is investigated] */
1196 /* chown (pty_name, getuid (), group_info->gr_gid); FIXME */
1197 /* chmod (pty_name, S_IRUSR | S_IWUSR | S_IWGRP); FIXME */
1199 if ((pty_slave
= open (pty_name
, O_RDWR
)) == -1)
1200 fprintf (stderr
, "open (pty_name, O_RDWR): %s\r\n", pty_name
);
1204 #endif /* !HAVE_GRANTPT */
1205 #endif /* HAVE_SUBSHELL_SUPPORT */