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.
23 #ifdef HAVE_SUBSHELL_SUPPORT
25 /* {{{ Declarations */
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 */
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. */
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 */
46 # include <unistd.h> /* For pipe, fork, setsid, access etc */
49 #ifdef HAVE_SYS_SELECT_H
50 # include <sys/select.h>
53 #ifdef HAVE_SYS_WAIT_H
54 # include <sys/wait.h> /* For waitpid() */
58 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
62 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
66 # include <stropts.h> /* For I_PUSH */
68 # include <grp.h> /* For the group struct & getgrnam() */
72 # include <grp.h> /* For the group struct & getgrnam() */
73 #endif /* SCO_FLAVOR */
76 # include <unix.h> /* exec*() from <process.h> */
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 */
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
);
99 # define STDIN_FILENO 0
102 #ifndef STDOUT_FILENO
103 # define STDOUT_FILENO 1
106 #ifndef STDERR_FILENO
107 # define STDERR_FILENO 2
110 /* If using a subshell for evaluating commands this is true */
112 #ifdef SUBSHELL_OPTIONAL
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 */
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
;
178 /* {{{ init_subshell */
181 * Fork the subshell, and set up many, many things.
183 * Possibly modifies the global variables:
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
191 # define SYNC_PTY_SIDES
193 # define SYNC_PTY_SIDES
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
)
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
];
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
;
224 if (subshell_pty
== 0) /* First time through */
226 /* {{{ Find out what type of shell we have */
228 if (strstr (shell
, "/zsh"))
230 else if (strstr (shell
, "/tcsh"))
231 subshell_type
= TCSH
;
232 else if (strstr (shell
, "/bash") || getenv ("BASH"))
233 subshell_type
= BASH
;
236 use_subshell
= FALSE
;
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
;
253 pty_slave
= pty_open_slave (pty_name
);
256 fprintf (stderr
, "couldn't open slave side of pty (%s)\n\r",
258 use_subshell
= FALSE
;
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
);
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
;
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
;
293 else /* subshell_type is BASH or ZSH */
294 if (pipe (subshell_pipe
))
296 perror (__FILE__
": couldn't create pipe");
297 use_subshell
= FALSE
;
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
);
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 */
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
);
356 /* {{{ Make sure that it has become our controlling terminal */
358 /* Redundant on Linux and probably most systems, but just in case: */
361 ioctl (pty_slave
, TIOCSCTTY
, 0);
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");
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
)
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");
415 init_file
= ".mc/tcshrc";
416 if (access (init_file
, R_OK
) == -1)
424 fprintf (stderr
, __FILE__
": unimplemented subshell type %d\n",
426 _exit (FORK_FAILURE
);
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
);
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
)
449 execl (shell
, "bash", "-rcfile", init_file
, NULL
);
453 execl (shell
, "tcsh", NULL
); /* What's the -rcfile equivalent? */
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
);
466 /* If we get this far, everything failed miserably */
467 _exit (FORK_FAILURE
);
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. */
482 /* {{{ Install our handler for 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
;
497 /* {{{ Set up `precmd' or equivalent for reading the subshell's CWD */
499 switch (subshell_type
)
501 char precmd
[BUF_SMALL
];
504 g_snprintf (precmd
, sizeof (precmd
), " PROMPT_COMMAND='pwd>&%d;kill -STOP $$'\n",
505 subshell_pipe
[WRITE
]);
509 g_snprintf (precmd
, sizeof (precmd
), "precmd(){ pwd>&%d;kill -STOP $$ }\n",
510 subshell_pipe
[WRITE
]);
514 g_snprintf (precmd
, sizeof (precmd
), "alias precmd 'echo $cwd:q >>%s;kill -STOP $$'\n", tcsh_fifo
);
517 write (subshell_pty
, precmd
, strlen (precmd
));
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 ();
530 use_subshell
= FALSE
; /* Subshell died instantly, so don't use it */
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
);
567 /* Make the subshell change to MC's working directory */
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 */
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
)
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};
619 FD_SET (subshell_pty
, &tmp
);
623 if (subshell_prompt
== NULL
) /* First time through */
625 subshell_prompt
= (char *) g_malloc (prompt_size
);
626 *subshell_prompt
= '\0';
630 while (subshell_alive
&&
631 (rc
= select (FD_SETSIZE
, &tmp
, NULL
, NULL
, &timeleft
)))
633 /* {{{ Check for `select' errors */
639 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
640 perror ("\n"__FILE__
": select (FD_SETSIZE, &tmp...)");
647 bytes
= read (subshell_pty
, pty_buffer
, pty_buffer_size
);
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'){
662 subshell_prompt
[prompt_pos
++] = pty_buffer
[i
];
663 if (prompt_pos
== prompt_size
)
664 subshell_prompt
= (char *) g_realloc (subshell_prompt
,
668 /* Sometimes we get an empty new line and then nothing,
669 * we better just keep the old prompt instead. */
671 subshell_prompt
[prompt_pos
] = '\0';
675 if (rc
== 0 && bytes
== 0)
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");
698 /* {{{ exit_subshell */
700 int exit_subshell (void)
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
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 ());
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
);
727 /* TCSH + AIX hang here, fix this before removing the ifdef above */
728 if (read (subshell_pipe
[READ
], pty_buffer
, pty_buffer_size
) == 5)
731 quit
= !query_dialog (_(" Warning "), _(" There are stopped jobs.")
732 _(" Quit anyway? "), 0, 2, _("&Yes"), _("&No"));
735 subshell_state
= RUNNING_COMMAND
;
736 feed_subshell (QUIETLY
, FALSE
); /* Drain the shell output (again) */
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");
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
)
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. */
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);
773 temp
= name_quote (directory
, 0);
774 write (subshell_pty
, temp
, strlen (temp
));
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
);
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 */
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
;
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
)
822 pid
= waitpid (subshell_pid
, &status
, WUNTRACED
| WNOHANG
);
824 if (pid
== subshell_pid
) {
825 /* {{{ Figure out what has happened to the subshell */
828 if (WIFSTOPPED (status
))
830 if (WSTOPSIG (status
) == SIGTSTP
)
831 /* The user has suspended the subshell. Revive it */
832 kill (subshell_pid
, SIGCONT
);
834 /* The subshell has received a SIGSTOP signal */
835 subshell_stopped
= TRUE
;
837 else /* The subshell has either exited normally or been killed */
840 subshell_alive
= FALSE
;
841 if (WIFEXITED (status
) && WEXITSTATUS (status
) != FORK_FAILURE
)
842 quit
|= SUBSHELL_EXIT
; /* Exited normally */
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 */
856 if (WIFSTOPPED (status
))
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. */
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 */
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
;
895 /* we wait up to 10 seconds if fail_on_error */
899 for (wptr
= fail_on_error
? &wtime
: NULL
;;)
904 /* {{{ Prepare the file-descriptor set and call `select' */
907 FD_SET (subshell_pty
, &read_set
);
908 FD_SET (subshell_pipe
[READ
], &read_set
);
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 */
916 continue; /* try all over again */
917 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
918 perror ("\n"__FILE__
": select (FD_SETSIZE, &read_set...)");
923 /* From now on: block forever on the select call */
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...)");
943 write (STDOUT_FILENO
, pty_buffer
, bytes
);
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);
955 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
956 perror ("\n"__FILE__
": read (subshell_pipe[READ]...)");
960 subshell_cwd
[bytes
-1] = 0; /* Squash the final '\n' */
964 subshell_ready
= TRUE
;
965 if (subshell_state
== RUNNING_COMMAND
)
967 subshell_state
= INACTIVE
;
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
);
981 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
982 perror ("\n"__FILE__
": read (STDIN_FILENO, pty_buffer...)");
986 for (i
=0; i
<bytes
; ++i
)
987 if (pty_buffer
[i
] == subshell_switch_key
)
989 write (subshell_pty
, pty_buffer
, i
);
991 subshell_state
= INACTIVE
;
995 write (subshell_pty
, pty_buffer
, bytes
);
996 subshell_ready
= FALSE
;
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
;
1024 kill (subshell_pid
, SIGCONT
);
1027 sigprocmask (SIG_SETMASK
, &old_mask
, NULL
);
1028 /* We can't do any better without modifying the shell(s) */
1032 /* {{{ pty opening functions */
1036 /* {{{ SCO version of pty_open_master */
1038 static int pty_open_master (char *pty_name
)
1044 strcpy (pty_name
, "/dev/ptyp");
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 */
1054 continue; /* Try next pty device */
1055 pty_name
[5] = 't'; /* Change "pty" to "tty" */
1056 if (access (pty_name
, 6)){
1063 return -1; /* Ran out of pty devices */
1067 /* {{{ SCO version of pty_open_slave */
1069 static int pty_open_slave (const char *pty_name
)
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)");
1090 /* {{{ System V version of pty_open_master */
1092 static int pty_open_master (char *pty_name
)
1099 /* getpt () is a GNU extension (glibc 2.1.x) */
1100 pty_master
= getpt ();
1102 strcpy (pty_name
, "/dev/ptmx");
1103 pty_master
= open (pty_name
, O_RDWR
);
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 */
1113 strcpy (pty_name
, slave_name
);
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)");
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\")");
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\")");
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\")");
1156 #endif /* sgi || __sgi */
1157 #endif /* I_FIND && I_PUSH */
1158 #endif /* __osf__ || linux || __linux__ */
1167 /* {{{ BSD version of pty_open_master */
1169 static int pty_open_master (char *pty_name
)
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 */
1187 continue; /* Try next pty device */
1188 pty_name
[5] = 't'; /* Change "pty" to "tty" */
1189 if (access (pty_name
, 6)){
1197 return -1; /* Ran out of pty devices */
1201 /* {{{ BSD version of pty_open_slave */
1203 static int pty_open_slave (const char *pty_name
)
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)");
1226 #endif /* HAVE_SUBSHELL_SUPPORT */
1228 /* {{{ Emacs local variables */
1231 Cause emacs to enter folding mode for this file: