1 /* Concurrent shell support for the Midnight Commander
2 Copyright (C) 1994, 1995, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
3 2005, 2006, 2007 Free Software Foundation, Inc.
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of Version 2 of the GNU General Public
7 License, as published by the Free Software Foundation.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * \brief Source: concurrent shell support
25 #ifdef HAVE_SUBSHELL_SUPPORT
28 # define _GNU_SOURCE 1
38 #include <sys/types.h>
40 #ifdef HAVE_SYS_IOCTL_H
41 # include <sys/ioctl.h>
47 # include <stropts.h> /* For I_PUSH */
48 #endif /* HAVE_STROPTS_H */
50 #include "lib/global.h"
51 #include "lib/tty/tty.h" /* LINES */
52 #include "lib/tty/key.h" /* XCTRL */
53 #include "lib/vfs/mc-vfs/vfs.h"
54 #include "lib/strutil.h"
55 #include "lib/fileloc.h"
57 #include "panel.h" /* current_panel */
58 #include "wtools.h" /* query_dialog() */
59 #include "main.h" /* do_update_prompt() */
60 #include "consaver/cons.saver.h" /* handle_console() */
64 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
68 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
71 /* tcsh closes all non-standard file descriptors, so we have to use a pipe */
72 static char tcsh_fifo
[128];
75 static void init_raw_mode (void);
76 static int feed_subshell (int how
, int fail_on_error
);
77 static void synchronize (void);
78 static int pty_open_master (char *pty_name
);
79 static int pty_open_slave (const char *pty_name
);
80 static int resize_tty (int fd
);
83 # define STDIN_FILENO 0
87 # define STDOUT_FILENO 1
91 # define STDERR_FILENO 2
94 /* If using a subshell for evaluating commands this is true */
96 #ifdef SUBSHELL_OPTIONAL
102 /* File descriptors of the pseudoterminal used by the subshell */
103 int subshell_pty
= 0;
104 static int subshell_pty_slave
= -1;
106 /* The key for switching back to MC from the subshell */
107 static const char subshell_switch_key
= XCTRL('o') & 255;
109 /* State of the subshell:
110 * INACTIVE: the default state; awaiting a command
111 * ACTIVE: remain in the shell until the user hits `subshell_switch_key'
112 * RUNNING_COMMAND: return to MC when the current command finishes */
113 enum subshell_state_enum subshell_state
;
115 /* Holds the latest prompt captured from the subshell */
116 char *subshell_prompt
= NULL
;
118 /* Initial length of the buffer for the subshell's prompt */
119 #define INITIAL_PROMPT_SIZE 10
121 /* Used by the child process to indicate failure to start the subshell */
122 #define FORK_FAILURE 69 /* Arbitrary */
124 /* Length of the buffer for all I/O with the subshell */
125 #define PTY_BUFFER_SIZE BUF_SMALL /* Arbitrary; but keep it >= 80 */
128 enum {READ
=0, WRITE
=1};
130 static char pty_buffer
[PTY_BUFFER_SIZE
] = "\0"; /* For reading/writing on the subshell's pty */
131 static int subshell_pipe
[2]; /* To pass CWD info from the subshell to MC */
132 static pid_t subshell_pid
= 1; /* The subshell's process ID */
133 static char subshell_cwd
[MC_MAXPATHLEN
+1]; /* One extra char for final '\n' */
135 /* Subshell type (gleaned from the SHELL environment variable, if available) */
143 /* Flag to indicate whether the subshell is ready for next command */
144 static int subshell_ready
;
146 /* The following two flags can be changed by the SIGCHLD handler. This is */
147 /* OK, because the `int' type is updated atomically on all known machines */
148 static volatile int subshell_alive
, subshell_stopped
;
150 /* We store the terminal's initial mode here so that we can configure
151 the pty similarly, and also so we can restore the real terminal to
152 sanity if we have to exit abruptly */
153 static struct termios shell_mode
;
155 /* This is a transparent mode for the terminal where MC is running on */
156 /* It is used when the shell is active, so that the control signals */
157 /* are delivered to the shell pty */
158 static struct termios raw_mode
;
160 /* This counter indicates how many characters of prompt we have read */
161 /* FIXME: try to figure out why this had to become global */
162 static int prompt_pos
;
166 * Write all data, even if the write() call is interrupted.
169 write_all (int fd
, const void *buf
, size_t count
)
174 ret
= write (fd
, (const unsigned char *) buf
+ written
, count
);
176 if (errno
== EINTR
) {
179 return written
> 0 ? written
: ret
;
189 * Prepare child process to running the shell and run it.
191 * Modifies the global variables (in the child process only):
197 init_subshell_child (const char *pty_name
)
199 const char *init_file
= NULL
;
203 setsid (); /* Get a fresh terminal session */
205 /* Make sure that it has become our controlling terminal */
207 /* Redundant on Linux and probably most systems, but just in case: */
210 ioctl (subshell_pty_slave
, TIOCSCTTY
, 0);
213 /* Configure its terminal modes and window size */
215 /* Set up the pty with the same termios flags as our own tty */
216 if (tcsetattr (subshell_pty_slave
, TCSANOW
, &shell_mode
)) {
217 fprintf (stderr
, "Cannot set pty terminal modes: %s\r\n",
218 unix_error_string (errno
));
219 _exit (FORK_FAILURE
);
222 /* Set the pty's size (80x25 by default on Linux) according to the */
223 /* size of the real terminal as calculated by ncurses, if possible */
224 resize_tty (subshell_pty_slave
);
226 /* Set up the subshell's environment and init file name */
228 /* It simplifies things to change to our home directory here, */
229 /* and the user's startup file may do a `cd' command anyway */
230 chdir (home_dir
); /* FIXME? What about when we re-run the subshell? */
232 /* Set MC_SID to prevent running one mc from another */
235 char sid_str
[BUF_SMALL
];
236 g_snprintf (sid_str
, sizeof (sid_str
), "MC_SID=%ld",
238 putenv (g_strdup (sid_str
));
241 switch (subshell_type
) {
243 init_file
= MC_USERCONF_DIR PATH_SEP_STR
"bashrc";
244 if (access (init_file
, R_OK
) == -1)
245 init_file
= ".bashrc";
247 /* Make MC's special commands not show up in bash's history */
248 putenv ((char*)"HISTCONTROL=ignorespace");
250 /* Allow alternative readline settings for MC */
251 if (access (MC_USERCONF_DIR PATH_SEP_STR
"inputrc", R_OK
) == 0)
252 putenv ((char*)"INPUTRC=" MC_USERCONF_DIR PATH_SEP_STR
"/inputrc");
256 /* TODO: Find a way to pass initfile to TCSH and ZSH */
263 fprintf (stderr
, __FILE__
": unimplemented subshell type %d\r\n",
265 _exit (FORK_FAILURE
);
268 /* Attach all our standard file descriptors to the pty */
270 /* This is done just before the fork, because stderr must still */
271 /* be connected to the real tty during the above error messages; */
272 /* otherwise the user will never see them. */
274 dup2 (subshell_pty_slave
, STDIN_FILENO
);
275 dup2 (subshell_pty_slave
, STDOUT_FILENO
);
276 dup2 (subshell_pty_slave
, STDERR_FILENO
);
278 close (subshell_pipe
[READ
]);
279 close (subshell_pty_slave
); /* These may be FD_CLOEXEC, but just in case... */
280 /* Close master side of pty. This is important; apart from */
281 /* freeing up the descriptor for use in the subshell, it also */
282 /* means that when MC exits, the subshell will get a SIGHUP and */
283 /* exit too, because there will be no more descriptors pointing */
284 /* at the master side of the pty and so it will disappear. */
285 close (subshell_pty
);
287 /* Execute the subshell at last */
289 switch (subshell_type
) {
291 execl (shell
, "bash", "-rcfile", init_file
, (char *) NULL
);
295 execl (shell
, "tcsh", (char *) NULL
);
299 /* Use -g to exclude cmds beginning with space from history
300 * and -Z to use the line editor on non-interactive term */
301 execl (shell
, "zsh", "-Z", "-g", (char *) NULL
);
306 execl (shell
, "fish", (char *) NULL
);
310 /* If we get this far, everything failed miserably */
311 _exit (FORK_FAILURE
);
316 * Check MC_SID to prevent running one mc from another.
318 * 0 if no parent mc in our session was found,
319 * 1 if parent mc was found and the user wants to continue,
320 * 2 if parent mc was found and the user wants to quit mc.
325 pid_t my_sid
, old_sid
;
329 sid_str
= getenv ("MC_SID");
333 old_sid
= (pid_t
) strtol (sid_str
, NULL
, 0);
341 /* The parent mc is in a different session, it's OK */
342 if (old_sid
!= my_sid
)
345 r
= query_dialog (_("Warning"),
346 _("GNU Midnight Commander is already\n"
347 "running on this terminal.\n"
348 "Subshell support will be disabled."), D_ERROR
, 2,
349 _("&OK"), _("&Quit"));
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
];
374 switch (check_sid ()) {
376 use_subshell
= FALSE
;
379 use_subshell
= FALSE
;
380 midnight_shutdown
= 1;
384 /* Take the current (hopefully pristine) tty mode and make */
385 /* a raw mode based on it now, before we do anything else with it */
388 if (subshell_pty
== 0) { /* First time through */
389 /* Find out what type of shell we have */
391 if (strstr (shell
, "/zsh") || getenv ("ZSH_VERSION"))
393 else if (strstr (shell
, "/tcsh"))
394 subshell_type
= TCSH
;
395 else if (strstr (shell
, "/csh"))
396 subshell_type
= TCSH
;
397 else if (strstr (shell
, "/bash") || getenv ("BASH"))
398 subshell_type
= BASH
;
399 else if (strstr (shell
, "/fish"))
400 subshell_type
= FISH
;
402 use_subshell
= FALSE
;
406 /* Open a pty for talking to the subshell */
408 /* FIXME: We may need to open a fresh pty each time on SVR4 */
410 subshell_pty
= pty_open_master (pty_name
);
411 if (subshell_pty
== -1) {
412 fprintf (stderr
, "Cannot open master side of pty: %s\r\n",
413 unix_error_string (errno
));
414 use_subshell
= FALSE
;
417 subshell_pty_slave
= pty_open_slave (pty_name
);
418 if (subshell_pty_slave
== -1) {
419 fprintf (stderr
, "Cannot open slave side of pty %s: %s\r\n",
420 pty_name
, unix_error_string (errno
));
421 use_subshell
= FALSE
;
425 /* Create a pipe for receiving the subshell's CWD */
427 if (subshell_type
== TCSH
) {
428 g_snprintf (tcsh_fifo
, sizeof (tcsh_fifo
), "%s/mc.pipe.%d",
429 mc_tmpdir (), (int) getpid ());
430 if (mkfifo (tcsh_fifo
, 0600) == -1) {
431 fprintf (stderr
, "mkfifo(%s) failed: %s\r\n", tcsh_fifo
,
432 unix_error_string (errno
));
433 use_subshell
= FALSE
;
437 /* Opening the FIFO as O_RDONLY or O_WRONLY causes deadlock */
439 if ((subshell_pipe
[READ
] = open (tcsh_fifo
, O_RDWR
)) == -1
440 || (subshell_pipe
[WRITE
] =
441 open (tcsh_fifo
, O_RDWR
)) == -1) {
442 fprintf (stderr
, _("Cannot open named pipe %s\n"), tcsh_fifo
);
443 perror (__FILE__
": open");
444 use_subshell
= FALSE
;
447 } else /* subshell_type is BASH or ZSH */ if (pipe (subshell_pipe
)) {
448 perror (__FILE__
": couldn't create pipe");
449 use_subshell
= FALSE
;
454 /* Fork the subshell */
456 subshell_alive
= TRUE
;
457 subshell_stopped
= FALSE
;
458 subshell_pid
= fork ();
460 if (subshell_pid
== -1) {
461 fprintf (stderr
, "Cannot spawn the subshell process: %s\r\n",
462 unix_error_string (errno
));
463 /* We exit here because, if the process table is full, the */
464 /* other method of running user commands won't work either */
468 if (subshell_pid
== 0) { /* We are in the child process */
469 init_subshell_child (pty_name
);
472 /* Set up `precmd' or equivalent for reading the subshell's CWD */
474 switch (subshell_type
) {
476 g_snprintf (precmd
, sizeof (precmd
),
477 " PROMPT_COMMAND='pwd>&%d;kill -STOP $$'\n",
478 subshell_pipe
[WRITE
]);
482 g_snprintf (precmd
, sizeof (precmd
),
483 " precmd(){ pwd>&%d;kill -STOP $$ }\n",
484 subshell_pipe
[WRITE
]);
488 g_snprintf (precmd
, sizeof (precmd
),
489 "set echo_style=both;"
490 "alias precmd 'echo $cwd:q >>%s;kill -STOP $$'\n",
494 g_snprintf (precmd
, sizeof (precmd
),
495 "function fish_prompt ; pwd>&%d;kill -STOP %%self; end\n",
496 subshell_pipe
[WRITE
]);
500 write_all (subshell_pty
, precmd
, strlen (precmd
));
502 /* Wait until the subshell has started up and processed the command */
504 subshell_state
= RUNNING_COMMAND
;
505 tty_enable_interrupt_key ();
506 if (!feed_subshell (QUIETLY
, TRUE
)) {
507 use_subshell
= FALSE
;
509 tty_disable_interrupt_key ();
511 use_subshell
= FALSE
; /* Subshell died instantly, so don't use it */
515 static void init_raw_mode ()
517 static int initialized
= 0;
519 /* MC calls tty_reset_shell_mode() in pre_exec() to set the real tty to its */
520 /* original settings. However, here we need to make this tty very raw, */
521 /* so that all keyboard signals, XON/XOFF, etc. will get through to the */
522 /* pty. So, instead of changing the code for execute(), pre_exec(), */
523 /* etc, we just set up the modes we need here, before each command. */
525 if (initialized
== 0) /* First time: initialise `raw_mode' */
527 tcgetattr (STDOUT_FILENO
, &raw_mode
);
528 raw_mode
.c_lflag
&= ~ICANON
; /* Disable line-editing chars, etc. */
529 raw_mode
.c_lflag
&= ~ISIG
; /* Disable intr, quit & suspend chars */
530 raw_mode
.c_lflag
&= ~ECHO
; /* Disable input echoing */
531 raw_mode
.c_iflag
&= ~IXON
; /* Pass ^S/^Q to subshell undisturbed */
532 raw_mode
.c_iflag
&= ~ICRNL
; /* Don't translate CRs into LFs */
533 raw_mode
.c_oflag
&= ~OPOST
; /* Don't postprocess output */
534 raw_mode
.c_cc
[VTIME
] = 0; /* IE: wait forever, and return as */
535 raw_mode
.c_cc
[VMIN
] = 1; /* soon as a character is available */
541 int invoke_subshell (const char *command
, int how
, char **new_dir
)
545 /* Make the MC terminal transparent */
546 tcsetattr (STDOUT_FILENO
, TCSANOW
, &raw_mode
);
548 /* Make the subshell change to MC's working directory */
550 do_subshell_chdir (current_panel
->cwd
, TRUE
, 1);
552 if (command
== NULL
) /* The user has done "C-o" from MC */
554 if (subshell_state
== INACTIVE
)
556 subshell_state
= ACTIVE
;
557 /* FIXME: possibly take out this hack; the user can
558 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 pcwd
= vfs_translate_path_n (current_panel
->cwd
);
577 if (new_dir
&& subshell_alive
&& strcmp (subshell_cwd
, pcwd
))
578 *new_dir
= subshell_cwd
; /* Make MC change to the subshell's CWD */
581 /* Restart the subshell if it has died by SIGHUP, SIGQUIT, etc. */
582 while (!subshell_alive
&& !quit
&& use_subshell
)
592 read_subshell_prompt (void)
594 static int prompt_size
= INITIAL_PROMPT_SIZE
;
595 int bytes
= 0, i
, rc
= 0;
596 struct timeval timeleft
= { 0, 0 };
600 FD_SET (subshell_pty
, &tmp
);
602 if (subshell_prompt
== NULL
) { /* First time through */
603 subshell_prompt
= g_malloc (prompt_size
);
604 *subshell_prompt
= '\0';
608 while (subshell_alive
610 select (subshell_pty
+ 1, &tmp
, NULL
, NULL
, &timeleft
))) {
611 /* Check for `select' errors */
616 fprintf (stderr
, "select (FD_SETSIZE, &tmp...): %s\r\n",
617 unix_error_string (errno
));
622 bytes
= read (subshell_pty
, pty_buffer
, sizeof (pty_buffer
));
624 /* Extract the prompt from the shell output */
626 for (i
= 0; i
< bytes
; ++i
)
627 if (pty_buffer
[i
] == '\n' || pty_buffer
[i
] == '\r') {
633 subshell_prompt
[prompt_pos
++] = pty_buffer
[i
];
634 if (prompt_pos
== prompt_size
)
636 g_realloc (subshell_prompt
, prompt_size
*= 2);
639 subshell_prompt
[prompt_pos
] = '\0';
641 if (rc
== 0 && bytes
== 0)
646 /* Resize given terminal using TIOCSWINSZ, return ioctl() result */
647 static int resize_tty (int fd
)
649 #if defined TIOCSWINSZ
650 struct winsize tty_size
;
652 tty_size
.ws_row
= LINES
;
653 tty_size
.ws_col
= COLS
;
654 tty_size
.ws_xpixel
= tty_size
.ws_ypixel
= 0;
656 return ioctl (fd
, TIOCSWINSZ
, &tty_size
);
662 /* Resize subshell_pty */
663 void resize_subshell (void)
665 if (use_subshell
== 0)
668 resize_tty (subshell_pty
);
674 int subshell_quit
= TRUE
;
676 if (subshell_state
!= INACTIVE
&& subshell_alive
)
678 !query_dialog (_("Warning"),
679 _(" The shell is still active. Quit anyway? "),
680 D_NORMAL
, 2, _("&Yes"), _("&No"));
683 if (subshell_type
== TCSH
) {
684 if (unlink (tcsh_fifo
) == -1)
685 fprintf (stderr
, "Cannot remove named pipe %s: %s\r\n",
686 tcsh_fifo
, unix_error_string (errno
));
689 g_free (subshell_prompt
);
690 subshell_prompt
= NULL
;
691 pty_buffer
[0] = '\0';
694 return subshell_quit
;
699 * Carefully quote directory name to allow entering any directory safely,
700 * no matter what weird characters it may contain in its name.
701 * NOTE: Treat directory name an untrusted data, don't allow it to cause
702 * executing any commands in the shell. Escape all control characters.
703 * Use following technique:
705 * printf(1) with format string containing a single conversion specifier,
706 * "b", and an argument which contains a copy of the string passed to
707 * subshell_name_quote() with all characters, except digits and letters,
708 * replaced by the backslash-escape sequence \0nnn, where "nnn" is the
709 * numeric value of the character converted to octal number.
711 * cd "`printf "%b" 'ABC\0nnnDEF\0nnnXYZ'`"
715 subshell_name_quote (const char *s
)
719 const char *quote_cmd_start
, *quote_cmd_end
;
722 if (subshell_type
== FISH
) {
723 quote_cmd_start
= "(printf \"%b\" '";
724 quote_cmd_end
= "')";
726 quote_cmd_start
= "\"`printf \"%b\" '";
727 quote_cmd_end
= "'`\"";
730 /* Factor 5 because we need \, 0 and 3 other digits per character. */
731 d
= ret
= g_try_malloc (1 + (5 * strlen (s
)) + (strlen(quote_cmd_start
))
732 + (strlen(quote_cmd_end
)));
736 /* Prevent interpreting leading `-' as a switch for `cd' */
742 /* Copy the beginning of the command to the buffer */
743 strcpy (d
, quote_cmd_start
);
744 d
+= strlen(quote_cmd_start
);
747 * Print every character except digits and letters as a backslash-escape
748 * sequence of the form \0nnn, where "nnn" is the numeric value of the
749 * character converted to octal number.
752 for (; su
[0] != '\0'; ) {
753 n
= str_cget_next_char_safe (su
);
754 if (str_isalnum (su
)) {
755 memcpy (d
, su
, n
- su
);
758 for (c
= 0; c
< n
- su
; c
++) {
759 sprintf (d
, "\\0%03o", (unsigned char) su
[c
]);
766 strcpy (d
, quote_cmd_end
);
772 /* If it actually changed the directory it returns true */
774 do_subshell_chdir (const char *directory
, int do_update
, int reset_prompt
)
780 pcwd
= vfs_translate_path_n (current_panel
->cwd
);
783 (subshell_state
== INACTIVE
784 && strcmp (subshell_cwd
, pcwd
))) {
785 /* We have to repaint the subshell prompt if we read it from
786 * the main program. Please note that in the code after this
787 * if, the cd command that is sent will make the subshell
788 * repaint the prompt, so we don't have to paint it. */
795 /* The initial space keeps this out of the command history (in bash
796 because we set "HISTCONTROL=ignorespace") */
797 write_all (subshell_pty
, " cd ", 4);
799 translate
= vfs_translate_path_n (directory
);
801 temp
= subshell_name_quote (translate
);
803 write_all (subshell_pty
, temp
, strlen (temp
));
806 /* Should not happen unless the directory name is so long
807 that we don't have memory to quote it. */
808 write_all (subshell_pty
, ".", 1);
812 write_all (subshell_pty
, ".", 1);
815 write_all (subshell_pty
, "/", 1);
817 write_all (subshell_pty
, "\n", 1);
819 subshell_state
= RUNNING_COMMAND
;
820 feed_subshell (QUIETLY
, FALSE
);
822 if (subshell_alive
) {
823 int bPathNotEq
= strcmp (subshell_cwd
, pcwd
);
825 if (bPathNotEq
&& subshell_type
== TCSH
) {
826 char rp_subshell_cwd
[PATH_MAX
];
827 char rp_current_panel_cwd
[PATH_MAX
];
829 char *p_subshell_cwd
=
830 mc_realpath (subshell_cwd
, rp_subshell_cwd
);
831 char *p_current_panel_cwd
=
832 mc_realpath (pcwd
, rp_current_panel_cwd
);
834 if (p_subshell_cwd
== NULL
)
835 p_subshell_cwd
= subshell_cwd
;
836 if (p_current_panel_cwd
== NULL
)
837 p_current_panel_cwd
= pcwd
;
838 bPathNotEq
= strcmp (p_subshell_cwd
, p_current_panel_cwd
);
841 if (bPathNotEq
&& strcmp (pcwd
, ".")) {
842 char *cwd
= strip_password (g_strdup (pcwd
), 1);
843 fprintf (stderr
, _("Warning: Cannot change to %s.\n"), cwd
);
850 update_prompt
= FALSE
;
853 /* Make sure that MC never stores the CWD in a silly format */
854 /* like /usr////lib/../bin, or the strcmp() above will fail */
859 subshell_get_console_attributes (void)
861 /* Get our current terminal modes */
863 if (tcgetattr (STDOUT_FILENO
, &shell_mode
)) {
864 fprintf (stderr
, "Cannot get terminal settings: %s\r\n",
865 unix_error_string (errno
));
866 use_subshell
= FALSE
;
872 /* Figure out whether the subshell has stopped, exited or been killed */
873 /* Possibly modifies: `subshell_alive', `subshell_stopped' and `quit' */
875 sigchld_handler (int sig
)
882 pid
= waitpid (subshell_pid
, &status
, WUNTRACED
| WNOHANG
);
884 if (pid
== subshell_pid
) {
885 /* Figure out what has happened to the subshell */
887 if (WIFSTOPPED (status
)) {
888 if (WSTOPSIG (status
) == SIGSTOP
) {
889 /* The subshell has received a SIGSTOP signal */
890 subshell_stopped
= TRUE
;
892 /* The user has suspended the subshell. Revive it */
893 kill (subshell_pid
, SIGCONT
);
896 /* The subshell has either exited normally or been killed */
897 subshell_alive
= FALSE
;
898 delete_select_channel (subshell_pty
);
899 if (WIFEXITED (status
) && WEXITSTATUS (status
) != FORK_FAILURE
)
900 quit
|= SUBSHELL_EXIT
; /* Exited normally */
904 pid
= waitpid (cons_saver_pid
, &status
, WUNTRACED
| WNOHANG
);
906 if (pid
== cons_saver_pid
) {
908 if (WIFSTOPPED (status
))
909 /* Someone has stopped cons.saver - restart it */
912 /* cons.saver has died - disable confole saving */
913 handle_console (CONSOLE_DONE
);
918 #endif /* __linux__ */
920 /* If we got here, some other child exited; ignore it */
924 /* Feed the subshell our keyboard input until it says it's finished */
926 feed_subshell (int how
, int fail_on_error
)
928 fd_set read_set
; /* For `select' */
930 int bytes
; /* For the return value from `read' */
931 int i
; /* Loop counter */
933 struct timeval wtime
; /* Maximum time we wait for the subshell */
934 struct timeval
*wptr
;
936 /* we wait up to 10 seconds if fail_on_error, forever otherwise */
939 wptr
= fail_on_error
? &wtime
: NULL
;
945 /* Prepare the file-descriptor set and call `select' */
948 FD_SET (subshell_pty
, &read_set
);
949 FD_SET (subshell_pipe
[READ
], &read_set
);
950 maxfdp
= max (subshell_pty
, subshell_pipe
[READ
]);
951 if (how
== VISIBLY
) {
952 FD_SET (STDIN_FILENO
, &read_set
);
953 maxfdp
= max (maxfdp
, STDIN_FILENO
);
956 if (select (maxfdp
+ 1, &read_set
, NULL
, NULL
, wptr
) == -1) {
958 /* Despite using SA_RESTART, we still have to check for this */
960 continue; /* try all over again */
961 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
962 fprintf (stderr
, "select (FD_SETSIZE, &read_set...): %s\r\n",
963 unix_error_string (errno
));
967 if (FD_ISSET (subshell_pty
, &read_set
))
968 /* Read from the subshell, write to stdout */
970 /* This loop improves performance by reducing context switches
971 by a factor of 20 or so... unfortunately, it also hangs MC
972 randomly, because of an apparent Linux bug. Investigate. */
973 /* for (i=0; i<5; ++i) * FIXME -- experimental */
975 bytes
= read (subshell_pty
, pty_buffer
, sizeof (pty_buffer
));
977 /* The subshell has died */
978 if (bytes
== -1 && errno
== EIO
&& !subshell_alive
)
982 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
983 fprintf (stderr
, "read (subshell_pty...): %s\r\n",
984 unix_error_string (errno
));
989 write_all (STDOUT_FILENO
, pty_buffer
, bytes
);
992 else if (FD_ISSET (subshell_pipe
[READ
], &read_set
))
993 /* Read the subshell's CWD and capture its prompt */
997 read (subshell_pipe
[READ
], subshell_cwd
,
1000 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
1001 fprintf (stderr
, "read (subshell_pipe[READ]...): %s\r\n",
1002 unix_error_string (errno
));
1006 subshell_cwd
[bytes
- 1] = 0; /* Squash the final '\n' */
1010 subshell_ready
= TRUE
;
1011 if (subshell_state
== RUNNING_COMMAND
) {
1012 subshell_state
= INACTIVE
;
1017 else if (FD_ISSET (STDIN_FILENO
, &read_set
))
1018 /* Read from stdin, write to the subshell */
1020 bytes
= read (STDIN_FILENO
, pty_buffer
, sizeof (pty_buffer
));
1022 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
1024 "read (STDIN_FILENO, pty_buffer...): %s\r\n",
1025 unix_error_string (errno
));
1029 for (i
= 0; i
< bytes
; ++i
)
1030 if (pty_buffer
[i
] == subshell_switch_key
) {
1031 write_all (subshell_pty
, pty_buffer
, i
);
1033 subshell_state
= INACTIVE
;
1037 write_all (subshell_pty
, pty_buffer
, bytes
);
1039 if (pty_buffer
[bytes
-1] == '\n' || pty_buffer
[bytes
-1] == '\r')
1040 subshell_ready
= FALSE
;
1048 /* Wait until the subshell dies or stops. If it stops, make it resume. */
1049 /* Possibly modifies the globals `subshell_alive' and `subshell_stopped' */
1050 static void synchronize (void)
1052 sigset_t sigchld_mask
, old_mask
;
1054 sigemptyset (&sigchld_mask
);
1055 sigaddset (&sigchld_mask
, SIGCHLD
);
1056 sigprocmask (SIG_BLOCK
, &sigchld_mask
, &old_mask
);
1059 * SIGCHLD should not be blocked, but we unblock it just in case.
1060 * This is known to be useful for cygwin 1.3.12 and older.
1062 sigdelset (&old_mask
, SIGCHLD
);
1064 /* Wait until the subshell has stopped */
1065 while (subshell_alive
&& !subshell_stopped
)
1066 sigsuspend (&old_mask
);
1068 if (subshell_state
!= ACTIVE
) {
1069 /* Discard all remaining data from stdin to the subshell */
1070 tcflush (subshell_pty_slave
, TCIFLUSH
);
1073 subshell_stopped
= FALSE
;
1074 kill (subshell_pid
, SIGCONT
);
1076 sigprocmask (SIG_SETMASK
, &old_mask
, NULL
);
1077 /* We can't do any better without modifying the shell(s) */
1080 /* pty opening functions */
1084 /* System V version of pty_open_master */
1086 static int pty_open_master (char *pty_name
)
1091 #ifdef HAVE_POSIX_OPENPT
1092 pty_master
= posix_openpt(O_RDWR
);
1094 /* getpt () is a GNU extension (glibc 2.1.x) */
1095 pty_master
= getpt ();
1097 strcpy (pty_name
, "/dev/ptc");
1098 pty_master
= open (pty_name
, O_RDWR
);
1100 strcpy (pty_name
, "/dev/ptmx");
1101 pty_master
= open (pty_name
, O_RDWR
);
1104 if (pty_master
== -1)
1107 if (grantpt (pty_master
) == -1 /* Grant access to slave */
1108 || unlockpt (pty_master
) == -1 /* Clear slave's lock flag */
1109 || !(slave_name
= ptsname (pty_master
))) /* Get slave's name */
1114 strcpy (pty_name
, slave_name
);
1118 /* System V version of pty_open_slave */
1120 pty_open_slave (const char *pty_name
)
1122 int pty_slave
= open (pty_name
, O_RDWR
);
1124 if (pty_slave
== -1) {
1125 fprintf (stderr
, "open (%s, O_RDWR): %s\r\n", pty_name
,
1126 unix_error_string (errno
));
1129 #if !defined(__osf__) && !defined(__linux__)
1130 #if defined (I_FIND) && defined (I_PUSH)
1131 if (!ioctl (pty_slave
, I_FIND
, "ptem"))
1132 if (ioctl (pty_slave
, I_PUSH
, "ptem") == -1) {
1133 fprintf (stderr
, "ioctl (%d, I_PUSH, \"ptem\") failed: %s\r\n",
1134 pty_slave
, unix_error_string (errno
));
1139 if (!ioctl (pty_slave
, I_FIND
, "ldterm"))
1140 if (ioctl (pty_slave
, I_PUSH
, "ldterm") == -1) {
1142 "ioctl (%d, I_PUSH, \"ldterm\") failed: %s\r\n",
1143 pty_slave
, unix_error_string (errno
));
1147 #if !defined(sgi) && !defined(__sgi)
1148 if (!ioctl (pty_slave
, I_FIND
, "ttcompat"))
1149 if (ioctl (pty_slave
, I_PUSH
, "ttcompat") == -1) {
1151 "ioctl (%d, I_PUSH, \"ttcompat\") failed: %s\r\n",
1152 pty_slave
, unix_error_string (errno
));
1156 #endif /* sgi || __sgi */
1157 #endif /* I_FIND && I_PUSH */
1158 #endif /* __osf__ || __linux__ */
1160 fcntl(pty_slave
, F_SETFD
, FD_CLOEXEC
);
1164 #else /* !HAVE_GRANTPT */
1166 /* BSD version of pty_open_master */
1167 static int pty_open_master (char *pty_name
)
1170 const char *ptr1
, *ptr2
;
1172 strcpy (pty_name
, "/dev/ptyXX");
1173 for (ptr1
= "pqrstuvwxyzPQRST"; *ptr1
; ++ptr1
)
1175 pty_name
[8] = *ptr1
;
1176 for (ptr2
= "0123456789abcdef"; *ptr2
; ++ptr2
)
1178 pty_name
[9] = *ptr2
;
1180 /* Try to open master */
1181 if ((pty_master
= open (pty_name
, O_RDWR
)) == -1) {
1182 if (errno
== ENOENT
) /* Different from EIO */
1183 return -1; /* Out of pty devices */
1185 continue; /* Try next pty device */
1187 pty_name
[5] = 't'; /* Change "pty" to "tty" */
1188 if (access (pty_name
, 6)){
1196 return -1; /* Ran out of pty devices */
1199 /* BSD version of pty_open_slave */
1201 pty_open_slave (const char *pty_name
)
1204 struct group
*group_info
= getgrnam ("tty");
1206 if (group_info
!= NULL
) {
1207 /* The following two calls will only succeed if we are root */
1208 /* [Commented out while permissions problem is investigated] */
1209 /* chown (pty_name, getuid (), group_info->gr_gid); FIXME */
1210 /* chmod (pty_name, S_IRUSR | S_IWUSR | S_IWGRP); FIXME */
1212 if ((pty_slave
= open (pty_name
, O_RDWR
)) == -1)
1213 fprintf (stderr
, "open (pty_name, O_RDWR): %s\r\n", pty_name
);
1214 fcntl(pty_slave
, F_SETFD
, FD_CLOEXEC
);
1218 #endif /* !HAVE_GRANTPT */
1219 #endif /* HAVE_SUBSHELL_SUPPORT */