Use SHLVL to determine if a shell is outermost.

This commit is contained in:
Jonas 'Sortie' Termansen 2014-06-20 01:06:41 +02:00
parent 242cfcca12
commit 46d16f9e4c
1 changed files with 23 additions and 11 deletions

View File

@ -1452,20 +1452,17 @@ bool does_line_editing_need_another_line(void*, const char* line)
return !is_shell_input_ready(line); return !is_shell_input_ready(line);
} }
bool is_parent_init() bool is_outermost_shell()
{ {
const char* init_pid_str = getenv("INIT_PID"); const char* shlvl_str = getenv("SHLVL");
if ( !init_pid_str) if ( !shlvl_str )
init_pid_str = "1"; return true;
pid_t init_pid = (pid_t) atol(init_pid_str); return atol(shlvl_str) <= 1;
if ( !init_pid )
init_pid = 1;
return getppid() == init_pid;
} }
void on_trap_eof(void* edit_state_ptr) void on_trap_eof(void* edit_state_ptr)
{ {
if ( is_parent_init() ) if ( is_outermost_shell() )
return; return;
struct edit_line* edit_state = (struct edit_line*) edit_state_ptr; struct edit_line* edit_state = (struct edit_line*) edit_state_ptr;
edit_line_type_codepoint(edit_state, L'e'); edit_line_type_codepoint(edit_state, L'e');
@ -1728,8 +1725,8 @@ int get_and_run_command_interactive(bool exit_on_error, bool* exitexec)
if ( edit_state.eof_condition ) if ( edit_state.eof_condition )
{ {
if ( is_parent_init() ) if ( is_outermost_shell() )
printf("Type exit to shutdown the system.\n"); printf("Type exit to close the outermost shell.\n");
else else
*exitexec = true; *exitexec = true;
} }
@ -1880,6 +1877,21 @@ int main(int argc, char* argv[])
argv[i] = argv[i+1]; argv[i] = argv[i+1];
argv[argc] = NULL; argv[argc] = NULL;
} }
if ( getenv("SHLVL") )
{
long shlvl = atol(getenv("SHLVL"));
if ( shlvl < 1 )
shlvl = 1;
else
shlvl++;
char shlvl_string[sizeof(long) * 3];
snprintf(shlvl_string, sizeof(shlvl_string), "%li", shlvl);
setenv("SHLVL", shlvl_string, 1);
}
else
{
setenv("SHLVL", "1", 1);
}
char pidstr[3 * sizeof(pid_t)]; char pidstr[3 * sizeof(pid_t)];
char ppidstr[3 * sizeof(pid_t)]; char ppidstr[3 * sizeof(pid_t)];
snprintf(pidstr, sizeof(pidstr), "%ji", (intmax_t) getpid()); snprintf(pidstr, sizeof(pidstr), "%ji", (intmax_t) getpid());