2

I am studying PTY, I have read The TTY demystified, What is a "coproc"?, and tested some code following this pattern like async, make parent process fork with new pseudo-terminal (PTY).

In the long term, I would like to understand ways of updating a prompt asynchronously, I have seen patterns like launching a parent process in the background (worker &) the use of zpty to feed/read the co-process, but still wondering why doing this within a own pty.

I have been testing mainly with zsh using this:

autoload -Uz async && async
async_init
typeset -Ag prompt_data

function zle-line-init zle-keymap-select prompt_refresh {
    PROMPT="$prompt_data[out] >> "
    zle reset-prompt
}

zle -N zle-line-init
zle -N zle-keymap-select

prompt_git(){
    sleep 3  # testing a delay
    if [ -n "$(cd $1 && git rev-parse --is-inside-work-tree 2>/dev/null)" ]; then
        git rev-parse --abbrev-ref HEAD
    fi
}

prompt_callback(){
    prompt_data[out]=$3
    prompt_refresh
}

async_start_worker 'prompt' -n
async_register_callback 'prompt' prompt_callback

prompt_precmd() {
    async_job 'prompt' prompt_git $(pwd)
}

autoload -Uz add-zsh-hook
add-zsh-hook precmd prompt_precmd

The example works, but still not clear for me the benefits/use cases of creating a parent that forks in a new PTY.

For doing IPC and avoiding PTY I was thinking about creating a named pipe, spawn a process that just reads the pipe but all this within the running PTY, therefore need help to better understand use cases and best practices about why and when using pseudo-terminals.

From this answer:

The child process created with os.fork() inherits stdin/stdout/stderr from parent process, while the child created with pty.fork() is connected to new pseudo terminal.

But still not clear what is the purpose of pty, it is only to isolate the child from the parent's stdin/stdout/stderr?

nbari
  • 25,603
  • 10
  • 76
  • 131

0 Answers0