Git Product home page Git Product logo

dtach's Introduction

1. INTRODUCTION

dtach is a program written in C that emulates the detach feature of
screen, which allows a program to be executed in an environment that is
protected from the controlling terminal. For instance, the program under
the control of dtach would not be affected by the terminal being
disconnected for some reason.

dtach was written because screen did not adequately meet my needs; I did
not need screen's extra features, such as support for multiple
terminals or terminal emulation support. screen was also too big,
bulky, and had source code that was difficult to understand.

screen also interfered with my use of full-screen applications such as
emacs and ircII, due to its excessive interpretation of the stream between
the program and the attached terminals. dtach does not have a terminal
emulation layer, and passes the raw output stream of the program to the
attached terminals. The only input processing that dtach does perform is
scanning for the detach character (which signals dtach to detach from
the program) and processing the suspend key (which tells dtach to
temporarily suspend itself without affecting the running program), and both
of these can both be disabled if desired.

Contrary to screen, dtach has minimal features, and is extremely tiny.
This allows dtach to be more easily audited for bugs and security
holes, and makes it accessible in environments where space is limited,
such as on rescue disks.

dtach has only been tested on the Linux/x86 platform, however it should
be easily portable to other variants of Unix. It currently assumes that
the host system uses POSIX termios, and has a working forkpty function
available.

dtach may need access to various devices in the filesystem depending on what
forkpty does. For example, dtach on Linux usually needs access to /dev/ptmx
and /dev/pts.

2. QUICK START

Compiling dtach should be simple, as it uses autoconf:

	$ ./configure
	$ make

If all goes well, a dtach binary should be built for your system. You can
then copy it to the appropriate place on your system.

dtach uses Unix-domain sockets to represent sessions; these are network
sockets that are stored in the filesystem. You specify the name of the
socket that dtach should use when creating or attaching to dtach sessions.

For example, let's create a new session that is running ircII. We will use
/tmp/foozle as the session's socket:

	$ dtach -A /tmp/foozle irc RuneB irc.freenode.net

Here, -A tells dtach to either create a new session or attach to the
existing session. If the session at /tmp/foozle does not exist yet, the
program will be executed. If it does exist, then dtach will attach to
the existing session.

dtach has another attach mode, which is specified by using -a. The -a
mode attaches to an already existing session, but will not create a new
session. Each attaching process can have a separate detach character,
suspend behavior, and redraw method, which are explained in the
following sections.

dtach is able to attach to the same session multiple times, though you
will likely encounter problems if your terminals have different window
sizes. Pressing ^L (Ctrl-L) will reset the window size of the program to
match the current terminal.

dtach also has a mode that copies the contents of standard input to a session.
For example:

	$ echo -ne 'cd /var/log\nls -l\n' | dtach -p /tmp/foozle

The contents are sent verbatim including any embedded control characters (e.g.
the newline characters in the above example), and dtach will not scan the
input for a detach character.

3. DETACHING FROM THE SESSION

By default, dtach scans the keyboard input looking for the detach character.
When the detach character is pressed, dtach will detach from the current
session and exit, leaving the program running in the background. You can then
re-attach to the program by running dtach again with -A or -a.

The default detach character is ^\ (Ctrl-\). This can be changed by supplying
the -e option to dtach when attaching. For example:

	$ dtach -a /tmp/foozle -e '^A'

That command would attach to the existing session at /tmp/foozle and use
^A (Ctrl-A) as the detach character, instead of the default ^\.

You can disable processing of the detach character by supplying the -E
option to dtach when attaching.

4. SUSPENDING DTACH

By default, dtach also processes the suspend key (^Z or Ctrl-Z) itself,
instead of passing it to the program. Thus, pressing suspend only suspends
the attaching process, instead of the running program. This can be very
useful for applications such as ircII, where you may not necessarily want
the program to be suspended.

Processing of the suspend key can be disabled by supplying the -z option
to dtach when attaching.

5. REDRAW METHOD

When attaching, dtach can use one of three methods to redraw the screen
(none, ctrl_l, or winch). By default, dtach uses the ctrl_l method,
which simply sends a ^L (Ctrl-L) character to the program if the
terminal is in character-at-a-time and no-echo mode. The winch method
forces a WINCH signal to be sent to the program, and the none method
disables redrawing completely.

For example, this command tells dtach to attach to a session at
/tmp/foozle and use the winch redraw method:

	$ dtach -a /tmp/foozle -r winch

When creating a new session (with the -c or -A modes), the specified
method is used as the default redraw method for the session.

6. CHANGES

The changes in version 0.9 are:
- Added AIX support.
- Added dtach -N, a mode similar to dtach -n, except dtach will stay in the
  foreground instead of daemonizing.
- Added dtach -p, which copies the contents of standard input to a session.
- dtach will no longer send 255 bytes of garbage to the program when read()
  returns an error.
- The executable bit is now set on the socket if clients are attached, and
  cleared when all clients have detached.
- The initial state of signals such as SIGPIPE are now preserved when
  executing the program, instead of having the program start with some signals
  ignored.
- A buffer overflow no longer occurs when a long socket path name is used, and
  dtach will now try to use chdir to get around the length limitation if
  necessary.

The changes in version 0.8 are:
- When using dtach -A or dtach -c, the master will now wait until the client
  attaches before trying to read from the program being executed. This avoids
  a race condition when the program prints something and exits before the
  client can attach itself.
- Instead of exiting quietly, dtach will now report any errors that occur
  while trying to execute the program.
- dtach -n can now be used without a terminal.
- dtach -A will now try to detect and remove stale sockets.
- Removed a Linux-specific escape sequence from the code that restores the
  original terminal settings.
- Changed dtach.1 to use \- for the dashes in command line options, and
  fix an ambiguous backslash.
- Use non-blocking mode in the master process, and avoid data loss by ensuring
  that at least one attaching client succesfully completes a write.
- Fix -e ^<char> to work with lowercase characters.

The changes in version 0.7 are:
- The redraw method can now be explicitly specified on the command line
  (either no redraw at all, the old ^L character method, and the new WINCH
  signal method), since many programs only handle one or the other properly.
- Changed the default redraw method back to the old ^L character method.
- Changed the attach code to check the return value of select more carefully.
- Changed the SIGWINCH handler to reinstall itself, to handle systems that
  always reset the handler.
- Added more proper process group handling.

The changes in version 0.6 are:
- Redraws are now handled by sending the child process a WINCH signal instead
  of by sending a ^L character. This should help prevent line-oriented
  programs (such as bash) from clearing the screen excessively.
- Flow control is now disabled when setting raw mode on the terminal.
- Switched to using select instead of poll.
- Changed some exits to exit succesfully instead of non-sucessfully.
- Updated my email address.
- Updated to Autoconf 2.59, renaming some files in the process.

The changes in version 0.5 are:
- Fix fd leakage.
- Prevent atexit from being called twice on dtach -A.

The changes in version 0.4 are:
- Slightly improved README and dtach.1
- Portability updates thanks to sourceforge's compile farm. dtach should now
  work on: FreeBSD, Debian/alpha, Debian/sparc, Debian/PPC, and Solaris.

The changes in version 0.3 are:
- Fixed a typo in dtach.1
- Changed the attach code so that it tells the master when a suspend
  occurs.
- Decreased the client <-> master packet size.
- Changed the master to send a stream of text to attaching clients
  instead of sending a huge packet all the time.
- Use getrlimit and dynamically allocate the data structures, if
  possible.
- Added some more autoconf checks.
- Initial sourceforge release.
 
7. AUTHOR

dtach is (C)Copyright 2004-2016 Ned T. Crigler, and is under the GNU General
Public License.

Comments and suggestions about dtach are welcome, and can be sent to
the author at: <[email protected]>.

dtach's People

Contributors

crigler avatar okurz avatar paul-wilkinson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dtach's Issues

Make issue: using -traditional without -E

Hello,

Here, when trying to compile dtach, gcc conplains that -traditional no longer works without -E.

GCC version used is 4.3.2.

Here is the complete error message:

gcc -traditional -L/opt/Python-2.7/lib -L/opt/Python-2.7/lib  -W -Wall -I.   -c -o attach.o attach.c
gcc: GNU C no longer supports -traditional without -E
make: *** [attach.o] Error 1

Adding the option in Makefile solve this issue though.

But, then it won't compile with the following error:

gcc -traditional -E -L/opt/Python-2.7/lib -L/opt/Python-2.7/lib  -W -Wall -I.   -c -o attach.o attach.c
In file included from /usr/include/features.h:348,
                 from /usr/include/errno.h:30,
                 from dtach.h:25,
                 from attach.c:20:
/usr/include/sys/cdefs.h:32: error: #error "You need a ISO C conforming compiler to use the glibc headers"
In file included from dtach.h:26,
                 from attach.c:20:
/usr/include/fcntl.h:183: error: #else after #else
/usr/include/fcntl.h:175: error: the conditional began here
/usr/include/fcntl.h:204: error: #else after #else
/usr/include/fcntl.h:197: error: the conditional began here
/usr/include/fcntl.h:211: error: #endif without #if
/usr/include/fcntl.h:222: error: #endif without #if
attach.c:61: error: detected recursion whilst expanding macro "SOCK_STREAM"
make: *** [attach.o] Error 1

I'm unsure why this is failing though.

dtach eats output of prev. commands

Type some commands to terminal. Then start dtach. Then exit from dtach. You will see all previous activity (i. e. before starting dtach) is disappeared (as opposed to screen and tmux).

$ dtach --version
dtach - version 0.9, compiled on May 21 2016 at 08:04:42.

Using -N argument with a terminal multiplexer in a TTY-less environment

While playing with dtach in a Docker container, I found that dtach -N <some socket> <some command> seems to exit silently when it's invoked in an environment which has no terminal (which is Docker's default) but works fine if I make Docker allocate a terminal. That would make sense for the -c mode, but I'd imagine that -N could theoretically work just fine when dtach is started in a "terminal-less" environment since it creates its own PTY for the command and never attaches to it. Is this just a side effect of how dtach currently handles terminals, or is there a fundamental limitation in the Linux APIs that would prevent dtach from functioning correctly in a terminal-less environment without daemonizing?

It's an easy enough fix in my own project to just allocate a terminal, but I figured I'd mention it in case you thought it was worth looking at eventually.

change mode on socket on detach

it would be nice if detach would allow for a way to figure out if a session is attached or not. screen uses the execute bit on the socket to document this: when a session is attached, it's executable, when it's not, it's not.

irssi can use that to automatically mark users as away for example.

can't find a way to run command inside session from script

Hi, I couldn't find any way to attach to a session and execute a command from a script. I tried searching for help or trying out stuff on my own, but nothing work, is there no way to do this? I found that screen has the -dm switches that serve for this purpose, so it'd be nice to have something similar.

Weird arrow key behavior when running rtorrent

I've been trying to set up a dtach session for rtorrent. dtach -n socket rtorrent; dtach -a socket works perfectly, but wierdly enough, when there's more than 1 second between the first command and the second, the up, down, right and left arrows are remapped to A, B, C and D respectively, and the terminal cursor is actually visible in the bottom left corner of rtorrent (it's normally invisible).

This means that dtach -n socket rtorrent; sleep 1; dtach -a socket isn't buggy, but dtach -n socket rtorrent; sleep 2; dtach -a socket is.

Every other program that I tried didn't get the bug, except vim, which would exit insert mode and throw an "E388: Couldn't find definition" error when any arrow key was pressed, but I'm not sure which key press that would be. I also tried xev, but the arrow key codes looked normal there.

I'm using st with $TERM set to xterm-256color. Also tried urxvt and xterm, and setting TERM to screen-256color. According to vim, $TERM doesn't change inside the dtach session though.
dtach version 0.9 (pacman version) on an up-to-date Arch Linux install.

Capturing STDOUT from dtach socket to a log file

I was wondering if it's possible to capture the STDOUT from dtach socket to a log file. The idea is to capture all the session into a log file that I can analyse later.

I have tried playing with socat but could not find the correct incantation. Is that even possible?

dtach -n always exits with -1 when the command exits

When ever dtach exits because the command started by dtach finishes it always seems to exit with -1 when started in dtach -n mode.

For example,

strace -s 8192 -ff ./dtach -n /tmp/f /bin/sh -c "sleep 1"

Produces the following snipped output,

<... select resumed> )                  = 1 (in [4])
--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=14569, si_uid=1000, si_status=0, si_utime=0, si_stime=0} ---
rt_sigreturn({mask=[]})                 = 1
read(4, 0x7ffdb1138830, 4096)           = -1 EIO (Input/output error)
unlink("/tmp/f")                        = 0
exit_group(1)                           = ?
+++ exited with 1 +++

dtach has extremely high CPU usage

Hello @crigler,

I'm noticing extremely high CPU usage for essentially idle dtach sessions.

# ps aux | head -n 1 ; ps aux | grep dtach
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root      1592  0.0  0.0  14220   992 pts/6    S+   23:22   0:00 grep --color=auto dtach
user      4111 42.7  0.0  14868   704 ?        Rs   May05 2177:36 dtach -A /home/user/save/irc zsh
user      4133 39.6  0.0   6288   388 pts/4    R+   May05 2015:43 dtach -A /home/user/save/irc zsh
user      4201  0.0  0.0  14868   700 ?        Ss   May05   0:01 dtach -A /home/user/save/irc zsh
# uptime
 23:23:30 up 45 days, 12:05,  3 users,  load average: 1.95, 1.69, 1.66

Here is what strace shows
select, read, write in a tight loop

select(4, [0 3], NULL, NULL, NULL)      = 1 (in [0])
read(0, "\3\rxe\f\f\3", 8)              = 7
write(3, "\0\7\3\rxe\f\f\3\0", 10)      = 10
select(4, [0 3], NULL, NULL, NULL)      = 1 (in [0])
read(0, "\3\rxe\f\f\3", 8)              = 7
write(3, "\0\7\3\rxe\f\f\3\0", 10)      = 10
select(4, [0 3], NULL, NULL, NULL)      = 1 (in [0])
read(0, "\3\rxe\f\f\3", 8)              = 7
write(3, "\0\7\3\rxe\f\f\3\0", 10)      = 10

Here is the process tree

systemd─┬─
        ├─dtach───zsh───dtach
        ├─dtach───zsh───irssi───{gmain}

Here is lsof for the two dtach sessoins


/home/user
/
/usr/bin/dtach
/lib/x86_64-linux-gnu/libnss_files-2.23.so
/lib/x86_64-linux-gnu/libnss_nis-2.23.so
/lib/x86_64-linux-gnu/libnsl-2.23.so
/lib/x86_64-linux-gnu/libnss_compat-2.23.so
/lib/x86_64-linux-gnu/libc-2.23.so
/lib/x86_64-linux-gnu/libutil-2.23.so
/lib/x86_64-linux-gnu/ld-2.23.so
/dev/null
/dev/null
/dev/null
/home/user/save/irc type=STREAM
/dev/ptmx
/home/user/save/irc type=STREAM
/home/user
/
/usr/bin/dtach
/lib/x86_64-linux-gnu/libc-2.23.so
/lib/x86_64-linux-gnu/libutil-2.23.so
/lib/x86_64-linux-gnu/ld-2.23.so
/dev/pts/4
/dev/pts/4
/dev/pts/4
type=STREAM
/home/user
/
/usr/bin/dtach
/lib/x86_64-linux-gnu/libnss_files-2.23.so
/lib/x86_64-linux-gnu/libnss_nis-2.23.so
/lib/x86_64-linux-gnu/libnsl-2.23.so
/lib/x86_64-linux-gnu/libnss_compat-2.23.so
/lib/x86_64-linux-gnu/libc-2.23.so
/lib/x86_64-linux-gnu/libutil-2.23.so
/lib/x86_64-linux-gnu/ld-2.23.so
/dev/null
/dev/null
/dev/null
/home/user/save/irc type=STREAM
/dev/ptmx

Version info...

# apt-cache policy dtach
dtach:
  Installed: 0.8-2.1
  Candidate: 0.8-2.1
  Version table:
 *** 0.8-2.1 500
        500 http://us.archive.ubuntu.com/ubuntu xenial/universe amd64 Packages
        100 /var/lib/dpkg/status

Make escape char permanently configurable

Currently, the escape char is ^\ which is impossible to type in with an European keyboard layout and two keys: German, French, Italian, etc. Though, one can use -e, it is extremely exhausting to provide this every time. Therefore, I propose to either move this to a compile time option: --with-escape-char=... or have an env var for that: DTACH_ESCAPE_CHAR. It would make life way easier for non-English users.

If we agree on some option, I can try to work out a patch.

Redirect stdout/stderr of the executed command when running as foreground

dtach -N /tmp/d1 echo "ASD" exits silently.

Let me explain an example where this is definitely a requirement. Consider the systemd unit as below:

[Unit]
Description=systemd integration for rtorrent using dtach - starts/stops rtorrent instances on startup/shutdown
Wants=network-online.target
After=network-online.target

[Service]
Environment="TERM=rxvt-unicode-256color"
KillMode=none
ExecStartPre=/usr/bin/mkdir -p %t/dtach
ExecStart=/usr/bin/dtach -N %t/dtach/rtorrent /usr/bin/rtorrent -n -o import=%E/rtorrent/.rtorrent.rc
ExecStop=/usr/bin/killall -u %u -w -s INT /usr/bin/rtorrent
# Refer https://github.com/crigler/dtach/issues/12, Success is error code 1
SuccessExitStatus=1

[Install]
WantedBy=default.target

Now what happens when rtorrent fails to start, say to due a config error? It prints to stderr/stdout. So will almost every cli program ranging from a simple echo to something heavy like rtorrent.

If I am running in foreground, then it would be prudent to redirect stdout/stderr of the command in question, or atleast have an option to do so.

Suggestion: Have an option that lists all the current sockets

As a user, I'm likely to forget what I called my socket when I created it. I'm also likely to forget that I created one, too.
An option to list the currently opened sockets, as well as highlighting the current session, would be really handy. Then I could look up the name of my socket if I forgot its name, and I could check to see if I was connected to a socket currently too.

Here's what I would imagine the output would look like:

Currently open sockets:
    socketname1 - /bin/bash (username1, joe, henry)
    vegetables - /usr/bin/carrot
    *browser - /usr/bin/elinks (sbrl)
    logs - tail -f /var/log/kern.log (logsrus)

The format I chose above was socketname - command[ (connectedusernames). The asterisk (*) in the above example denotes the current session. Perhaps the current session could be made bold, too?

Previous terminal output is cleared on reattaching

Hi @crigler

I have been using dtach in a program that I use for executing commands with a long execution time on an Amazon EC2 instance. Due to the instance sometimes being unresponsive, I periodically detach and reattach to the session via my script. It has been working great in general. The only issue I have is that whatever is printed on my local terminal from the redirected output from the instance gets cleared when the session reattaches. So I am not able to see all the output from the session in one place. Is there an easy way to not clear the prior output?

Thanks a lot!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.