Attaching from inside of screen что делать
GNU Screen is a simple, but at the same time flexible and programmable windows manager. It is often called terminal multiplexer, but the key functionality of screen is in the area of windows management: creation, destruction and resizing of windows. For example it can split the console screen horizontally and display two windows at the same time. Screen is a Unix program (Cygwin version exists and is quite usable). For good Windows terminal emulator see Teraterm
Authodetach capability
One of the most important) feature of screen is that like VNC it provides the ability to detach the terminal emulator from the running programs and then reattach the same or new terminal to them.
Autodetach setting might not be enabled by default so it make sense to put a corresponding directive in your .screenrc
Detaching and reattaching
You can detach just by closing the terminal emulator that contains the session. Neither of these actually end your session. All they do is unbind your session from the current terminal. All of the programs you started running within screen are still running.
To reattach outside the screen type
You can also use the command:
you can attach with just the pid i.e. screen -r 12345
To join a screen that is already attached
Will attach you to that screen. In this case you have two session for the same UserID. Both users have control so be careful.
Naming screen sessions
Assuming you want named sessions for clarity, you can name a session in screen by starting screen as:
You can then reattach to a session using:
or kill/quit a session using:
Summary
List available screen sessions
Reconnect to specific session
- If there is a single session only screen -x will suffice.
- Otherwise you need to provide the name of the screen session
Connect to specific session in "watching/spy mode"
If there is a single session only screen -x will suffice.
you can attach with just the pid i.e. screen -r 12345
Reattaching to session within the screen
Dr. Nikolai Bezroukov
Your browser does not support iframes.
Reference
NEWS CONTENTS
Manpage
[GNU screen manpage]
[Stolen pretty much verbatim from the man page. <PMG>]Each window in a screen session emulates a VT100 terminal, with some extra functions added. The VT100 emulator is hardcoded; no other terminal types can be emulated.
Usually screen tries to emulate as much of the VT100/ANSI standard as possible. But if your terminal lacks certain capabilities, the emulation may not be complete. In these cases screen has to tell the applications that some of the features are missing. This is no problem on machines using termcap, because screen can use the $TERMCAP variable to customize the standard screen termcap.
But if you do a rlogin on another machine or your machine supports only terminfo this method fails. Because of this, screen offers a way to deal with these cases. Here is how it works:
When screen tries to figure out a terminal name for itself, it first looks for an entry named "screen.<term>", where <term> is the contents of your $TERM variable. If no such entry exists, screen tries "screen" (or "screen-w" if the terminal is wide (132 cols or more)). If even this entry cannot be found, "vt100" is used as a substitute.
The idea is that if you have a terminal which doesn't support an important feature (e.g. delete char or clear to EOS) you can build a new termcap/terminfo entry for screen (named "screen.<dumbterm>") in which this capability has been disabled. If this entry is installed on your machines you are able to do a rlogin and still keep the correct termcap/terminfo entry. The terminal name is put in the $TERM variable of all new windows. Screen also sets the $TERMCAP variable reflecting the capabilities of the virtual terminal emulated. Notice that, however, on machines using the terminfo database this variable has no effect. Furthermore, the variable $WINDOW is set to the window number of each window.
The actual set of capabilities supported by the virtual terminal depends on the capabilities supported by the physical terminal. If, for instance, the physical terminal does not support underscore mode, screen does not put the us and ue capabilities into the window's $TERMCAP variable, accordingly. However, a minimum number of capabilities must be supported by a terminal in order to run screen; namely scrolling, clear screen, and direct cursor addressing (in addition, screen does not run on hardcopy terminals or on terminals that overstrike).
Also, you can customize the $TERMCAP value used by screen by using the "termcap" .screenrc command, or by defining the variable $SCREENCAP prior to startup. When the is latter defined, its value will be copied verbatim into each window's $TERMCAP variable. This can either be the full terminal definition, or a filename where the terminal "screen" (and/or "screen-w") is defined.
Note that screen honors the "terminfo" .screenrc command if the system uses the terminfo database rather than termcap.
When the po and pf capabilities are present in the terminal's termcap entry, applications running in a screen window can send output to the printer port of the terminal. This allows a user to have an application in one window sending output to a printer connected to the terminal, while all other windows are still active (the printer port is enabled and disabled again for each chunk of output). As a side-effect, programs running in different windows can send output to the printer simultaneously. Data sent to the printer is not displayed in the window. The info command displays a line starting 'PRIN' while the printer is active.
Screen maintains a hardstatus line for every window. If a window gets selected, the display's hardstatus will be updated to match the window's hardstatus line. If the display has no hardstatus the line will be displayed as a standard screen message. The hardstatus line can be changed with the ANSI Application Program Command (APC): ESC_<string>ESC\. As a convenience for xterm users the sequence ESC]0..2;<string>^G is also accepted.
Some capabilities are only put into the $TERMCAP variable of the virtual terminal if they can be efficiently implemented by the physical terminal. For instance, dl (delete line) is only put into the $TERMCAP variable if the terminal supports either delete line itself or scrolling regions. Note that this may provoke confusion, when the session is reattached on a different terminal, as the value of $TERMCAP cannot be modified by parent processes.
The "alternate screen" capability is not enabled by default. Set the altscreen .screenrc command to enable it.
The following is a list of control sequences recognized by screen. "(V)" and "(A)" indicate VT100-specific and ANSI- or ISO -specific functions, respectively.
I am working on a remote Debian Jessie server. I have started a screen session, started running a script, then been disconnected by a network timeout.
Now I have logged in again and want to resume the session.
This is what I see when I list screens:
I seem to be attached to two screens at once.
Now I want to resume the session I was running before, to see the results of my script:
Why I can't I re-attach?
I have the same problem with the other screen:
2,623 4 4 gold badges 13 13 silver badges 13 13 bronze badgesHiveOS Скрипт автоуправления вентиляторами Nvidia на HiveOS
в том то и дело, что нету, ни путти ни внц ни шелинбокс не работают, хз почему. риг на проводе, бук на вай-вае, порты пытался пробросить, но ничего не получилось, роутер китайское овно (зте), ни одна инструкция не подошла, ну или я что-то не то не там делал
кому не нравится вин - вот вам реф на хайвос или рейвос , помогу настроиться)
Steambot
Свой человек
в том то и дело, что нету, ни путти ни внц ни шелинбокс не работают, хз почему. риг на проводе, бук на вай-вае, порты пытался пробросить, но ничего не получилось, роутер китайское овно (зте), ни одна инструкция не подошла, ну или я что-то не то не там делал
Steambot
Свой человек
А как быть если Хайв на флешке, там такой папки нет
не важно на чем хайв. подключаешься по ssh или монитор включи к ригу локально, и загружай.
alexzhila
Пляшущий с бубном
Добрый день! Все сделал как написали, залил два файла, изменил (исполнение 755 ), но не хочет запускать скрипт, что только не делал, Version: 0.5-52. Подскажите, может на последней версии не работает?
Вложения
Steambot
Свой человек
возможно: Once you are in run sudo -s to become root user. Start or stop miners, agent, etc only from root user.
попробуйте просто запустить ./autofan.sh
Steambot
Свой человек
Version: 0.5-52. Подскажите, может на последней версии не работает?
Kapitalizm
Друг форума
подключен) но я как бы не силен в юниксах, так что от этого скрипт туда не попал) я алекса просил о помощи, но ни ответа ни привета( если ты знаешь, как сделать, как скрипт этот запилить на рига, чиркани в личку. спасибо
кому не нравится вин - вот вам реф на хайвос или рейвос , помогу настроиться)
alexzhila
Пляшущий с бубном
Спасибо большое! Да заработало, только как теперь его в автозапуск поставить? Перезагрузил, не запускается.
Steambot
Свой человек
Спасибо большое! Да заработало, только как теперь его в автозапуск поставить? Перезагрузил, не запускается.
alexzhila
Пляшущий с бубном
В
В фоне не запускается, (sudo -s выполнить) можно пж. подробней?, просто в линуксе полнейший ноль.
Steambot
Свой человек
просто набери sudo -s и ввод. потом screen -dmS autofan /home/user/autofan.sh
screen -ls
alexzhila
Пляшущий с бубном
просто набери sudo -s и ввод. потом screen -dmS autofan /home/user/autofan.sh
screen -ls
Вложения
Steambot
Свой человек
alexzhila
Пляшущий с бубном
Вложения
Steambot
Свой человек
ерунда какая-то. у всех работает. должно грузиться. отписал в личку.
Steambot
Свой человек
ерунда какая-то. у всех работает. должно грузиться. отписал в личку.
проблему решил. все дело в том, что пользователь отредактировал файл под виндоус, а потом пытался запустить. так работать не будет (будет, если ваш редактор умеет переводить в никс формат). поэтому редактируйте файлы на риге редактором nano. также есть в хайве встроенный менеджер файлов, команда mc и там по F4 можно также редактировать файлы.
alexzhila
Пляшущий с бубном
Огромнейшее спасибо! Все теперь прекрасно работает! Побольше таких людей бы на форуме. Очень помогли.
Gam10001
Пляшущий с бубном
проблему решил. все дело в том, что пользователь отредактировал файл под виндоус, а потом пытался запустить. так работать не будет (будет, если ваш редактор умеет переводить в никс формат). поэтому редактируйте файлы на риге редактором nano. также есть в хайве встроенный менеджер файлов, команда mc и там по F4 можно также редактировать файлы.
Не получается в самом хайве отредактировать )
не запускается после перезапуска
не получается справится с задачей)
в mc не выставляются права , а с nano не получилось разобраться
Continued.
Mrxvt version 0.4.0 is released!
Вышел первый по настоящему стабильный релиз эмулятора терминала mrxvt.
Отличительной особенностью данной программы является наличие табов и минимальные системные зависимости.
Один раз уже удалили. скажу еще раз.
Эта мадам знает никсы на порядок лучще тебя, можешь быть уверен.
Флэйм разводишь ты, тоже мне новость. мрхвт. да, юзали гдето месяца 4 назад.. и матерм, и мрхвт. имхо -- КАКА, оба.
согласен, я тоже не вижу разницы.
У меня все равно с какими ключами пляшет от
0.25s real 0.04s user 0.03s system
1.59s real 0.03s user 0.04s system
Сколько у тебя девов в /dev??
>Флэйм разводишь ты, тоже мне новость. мрхвт. да, юзали гдето месяца >4 назад.. и матерм, и мрхвт. имхо -- КАКА, оба.
Гы, обидился. :)))
Четыре месяца назад, это действительно было длстаточно глючно.
А по поводу мадам.
>тупая и не нужная прога. имхо юзать нужно простой хтерм или атерм с screen. нафига эти тупые табы?
Это что признак глубокого знания Никсов .
>Сколько у тебя девов в /dev??
$ ls -al /dev/ | wc -l
706
ls у меня это alias на ls -lSr -h -CF --color , то бишь вывод в цвете.
>Это что признак глубокого знания Никсов .
>Лана шутю я. :)
да какие тут шутки. :)))
>Чего удивлятся? Attaching from inside of screen. а ты чего ждал?
Этого и ждал. Не видишь проблемы? screen в screen'e не катит. Я screen использую только для ctrl+d, а за табы отвечает сам терминал. Это, в отличии от скрина, не создает кучу проблем, особенно если в каком-то из табов надо сделать screen -x.
только что попробовал screen -x <session_id> внутри скрина прекрасно работает. Единственно screen внутри скрина это неудобно в использовании.. Я для разных скринов открываю разные окна, их редко бывает больше 2.
лол. как ты хочешь чтобы работал скрин в скрине? чтобы они биндили оба кнопки Ctl+a?? чувак.. настрой сначало скрин нормально, а потом уже говори что это не удобно..
ИМХО в сто раз удобнее юзать голый скрин деленый на два фрейма а не 2 таба в эмуляторе терминала.
Тестируя разные терминалы на скорость вывода явно задавайте одинаковые: - фонты (читабельные, 9x15, например)
- размер буфера для скроллинга (строк так тысячи три хотя бы, иначе совсем неинтересно)
- строк вывода побольше; 20-50 тысяч - наглядней будет :)
ls -alR /usr | head -30000 > ls-test
time -p cat ls-test
Иначе получится как соревнования по гимнастике c проамериканским жюри :)
-j и -s - на личное усмотрение. Странно, -j для xterm немного ускоряет вывод, а в rxvt наоборот притормаживает.
как aterm в сравнении с rxvt?
Кроме скорости есть другие фичи, в gnome-terminal есть смена кодировки, кто-то из терминалок еще умеет это делать? Имеется в виду с изменением key-maping, а не только сменой фонта.
> mrxvt*termName: xterm > не работает home end
mrxvt*keysym.0xFF50: \EOH mrxvt*keysym.0xFF57: \EOF
Да вот под Винду бы найти похожую. Может кто посоветует .
А то и вправду когда 10 окошек в PuTTY откроешь начинаешь путаться :(
что то у вас в консерватории того. у меня konsole меньше 1% хавает цпу
читать man. весь кде для konsole ставить не нужно. более того то что нудо поставить используется многими полезными программами.
No manual entry for screen
> Вкладки рулят, еще бы под винду что-нить подобное, а то в 5 окошек putty тыркаться напрягает.
Лучше посоветуйте программу под X, которая умела бы склеивать несколько окон одинакового размера в одно окно с табами. И позволяла бы с помощью этих табов переключаться между склеенными окнами.
Хочу запустить десяток xterm внутри такой программы и переключаться между ними.
> man screen
> No manual entry for screen
apt-get install screen
> у меня konsole меньше 1% хавает цпу
> Лучше посоветуйте программу под X, которая умела бы склеивать несколько окон
> Хочу запустить десяток xterm внутри такой программы и переключаться между ними.
здесь-же почти сразу и сказали. :
> можно юзать флуксбокс с его табами,
> ShellGuard
Ну и туфта этот ShellGuard. Лучше уж на PuTTY оставаться. :(
> Ну и туфта этот ShellGuard. Лучше уж на PuTTY оставаться. :(
Ну и туфта этот PuTTY. Лучше уж на ShellGuard оставаться.
Меня не перестаёт радовать уровень дискуссий на ЛОР.
флуксбокс - это сильно тяжелее одной-единственной программы.
Да и от привычного интерфейса уходить не хочу.
тогда наверно [xae]term'ы будут 0% потреблять? :)
> У меня нету этого бага.
Проблема с повисанием mc при F3 внутри tar.bz2 пофикшена. С новым command.c всё работает прекрасно. См. sourceforge tracker system.
ok, I can now repeat your problem now. it seems to happen only for bash, not csh. and I must set the environment variables as yours. it seems that the mrxvt process is trying to read data from the mc process, but the reading is blocked (the mc process does not give any hint to the mrxvt process that all data have been sent). I still do not understand why it happens in this way since in C shell everything is fine. :-(
User Manual
Recommended Links
Google matched content
Softpanorama Recommended
Top articles
Sites
Red Hat Magazine A guide to GNU Screen
Solaris Packages
- screen-4.0.2-sol10-sparCtrl-local.gz Screen provides an ANSI/vt100 terminal emulator, which can multiplex up to 10 pseudo-terminals - installs in /usr/local. There are further configuration steps in the /usr/local/doc/screen/INSTALL. The etc and terminfo directories containing other relevant files are in /usr/local/doc/screen. The screen package may also require that you install the ncurses package.
3 Answers 3
The session is still attached on another terminal. The server hasn't detected the network outage on that connection: it only detects the outage when it tries to send a packet and gets an error back or no response after a timeout, but this hasn't happened yet. You're in a common situation where the client detected the outage because it tried to send some input and failed, but the server is just sitting there waiting for input. Eventually the server will send a keepalive packet and detect that the connection is dead.
In the meantime, use the -d option to detach the screen session from the terminal where it's in.
screen -rd is pretty much the standard way to attach to an existing screen session.
According to the manual you can "resume" only detached screens:
‘ -ls [match]’
‘ -list [match]’
Do not start screen, but instead print a list of session identification strings (usually of the form pid.tty.host; see Session Name). Sessions marked ‘detached’ can be resumed with screen -r . Those marked ‘attached’ are running and have a controlling terminal. If the session runs in multiuser mode, it is marked ‘multi’. Sessions marked as ‘unreachable’ either live on a different host or are dead. An unreachable session is considered dead, when its name matches either the name of the local host, or the specified parameter, if any. See the -r flag for a description how to construct matches. Sessions marked as ‘dead’ should be thoroughly checked and removed. Ask your system administrator if you are not sure. Remove sessions with the ‘ -wipe ’ option.
What you want is this option:
‘ -x ’
Attach to a session which is already attached elsewhere (multi-display mode). Screen refuses to attach from within itself. But when cascading multiple screens, loops are not detected; take care.
Old News ;-)
[Dec 12, 2019] command line - Reattaching to an existing screen session - Ask Ubuntu
There are two levels of "listings" involved here. First, you have the "window listing" within an individual session, which is what ctrl-A A is for, and second there is a "session listing" which is what you have pasted in your question and what can also be viewed with screen -ls .You can customize the session names with the -S parameter, otherwise it uses your hostname (teamviggy), for example:
(ctrl-A d to detach)
(ctrl-A d to detach)
As a bonus, you can use an unambiguous abbreviation of the name you pass to -S later to reconnect:
(I am reconnected to the myprogramrunningunderscreen session)
I had a case where screen -r failed to reattach. Adding the -d flag so it looked like thisworked for me. It detached the previous screen and allowed me to reattach. See the Man Page for more information.
An easy way is to simply reconnect to an arbitrary screen withThen once you are running screen, you can get a list of all active screens by hitting Ctrl-A " (i.e. control-A followed by a double quote). Then you can just select the active screens one at a time and see what they are running. Naming the screens will, of course, make it easier to identify the right one.
Just my two cents
Lefty G Balogh ,
The output of screen -list is formatted like pid.tty.host . The pids can be used to get the first child process with pstree :You will get a list like this
[Nov 02, 2018] How to Recover from an Accidental SSH Disconnection on Linux RoseHosting
[Solved] screen autodetach problem
The FreeBSD Forums
[Jan 23, 2012] A guide to GNU Screen by Steve 'Ashcrow' Milner and Anderson Silva
October 5, 2007 Red Hat Magazine
/.screenrc to meet your needs.
My
Hey Richard!:
With the 'at' command, you can send commands to other windows that have to be typed when you press C-a :
This changes the title of a window in a certain screen session:
screen -X at 1 title blublublu
Rob Nichols:
This is a great intro. I've used screen for many years. (Just stopped to count. I think it's been a decade!) However, I'd never bothered with learning about the hardstatus line until this article. It's a nice addition. Thanks!
P.S. I think there are two mistakes in the example given. Again, this is my first foray in screen's string escapes, so I might be way off. I think "%" should have a space, as "%". Without this change on my system windows before the current are green instead of white. I also think there is an extra "%?" before the the closing "]" on the window list. This made no difference on my system. Here's a version with these changes.
hardstatus string '%[ %%H %][%= %%?%-Lw%?%(%%n*%f%t%?(%u)%?%)%%?%+Lw%?%= %][%%Y-%m-%d %%c %]'
I've used Screen for more than a decade. For years now I've used it to keep open ssh sessions to various systems, doing things like tailing logs and such, and disconnecting then reconnecting when necessary. My latest session has been running upwards of 2 years, only ever bringing it down for critical patching. Sometimes I connect to the same session from multiple windows, displaying different screen "windows" for multiple views. I also use an always on statis as well.
The few modifications I've made are to increase the MAXWIN param to allow for more windows, and change the command key to ^w so I don't have to unlearn my emacs ^a habits.
One good use of Screen is when performing remote updates of systems using apt-get or yum. You can start the update going, then disconnect, then come back later and check that it finished OK. If your remote connection goes down, it doesn't mess everything up. Also, using the screen 'logging' function, you can keep a full history of the update, and check it for error messages that you might have missed.
[Oct 19, 2010] Make GNU Screen Your Default Shell
george >: -[This is an interesting idea --NNB]
Instead, I first login and create a screen session called main using screen -S main
- Start Screen: screen
- Detatch Screen: Ctrl-a d
- Re-attach Screen: screen -x or screen -x PID
- Split Horizontally: Ctrl-a S
- Split Vertically: Ctrl-a |
- Move Between Windows: Ctrl-a Tab
- Name Session: Ctrl-a A
- Log Session: Ctrl-a H
- Note Session: Ctrl-a h
[Jun 27, 2010] switching from gnu screen to tmux (updated)
Linux
Selected Comments
Dan Douglas:
You probably had mouse-select-pane set to on. That way, tmux grabs the mouse click. You can still hold down the shift key to mark things by clicking and dragging Not sure if you can make tmux define a protected region though.
Join-pane and break-pane work as advertised in 1.2.
I don't use splitting much on localhost either, since I'm using the awesome window manager, but splitting is very useful when doing work over ssh
Dan Douglas:
Yeah splitting is definitely useful over ssh. That's primarily why I started using it.
I tried turning mouse-select-pane off. I had a chat with one of the tmux devs on irc a few months ago and apparently the problem is simply that they don't implement that yet. My workaround was setting a hotkey in vim to turn line numbers on and off so it's possible to copy/paste between a browser window without having to abuse xclip too much.
I didn't realize Screen was that hard on resources either. Kinda stinks. I've been using Konsole too which apparently isn't so lightweight. I like it though since I have kde installed anyway and has always worked flawlessly.
I've switched to tmux recently too, but I'm not that advanced user, so the only thing bothering me is that I can't figure out how to do something similar to `screen -RD`. If remote box has been rebooted, I don't want to run `tmux attach`, then see it failing, run `tmux` and then reattach to it again. I think it could be somehow worked around, but didn't succed myself.
you could define an alias (or write a small bash script) that does that automatically:
alias mytmux="tmux a -d || tmux"
The biggest memory saving I made on my machine recently was switching away from gnome-terminal to urxvt(d). I've never really noticed much of a memory issue with screen although I do wish it was easier to script/configure. I shall check out tmux when I next have a spare few hours
well, if your needs are satisfied with dtach, then sure, the others are bloatware for you! I, on the other hand, actually use their features
I don't know why your 'screen' use is bloated. This is from a 256 MiB home server:
F S UID PID PPID C PRI NI ADDR SZ WCHAN STIME TTY TIME CMD
1 S tzot 3215 1 0 80 0 � 1319 ? May01 ? 00:00:03 SCREEN -A -a -U
0 S tzot 32215 32214 0 80 0 � 1018 ? 11:32 pts/0 00:00:00 screen -A -a -U -D -r 321Its size is 100�25, four bash/dash sessions plus one mc session, no
/.screenrc, the default /etc/screenrc has defscrollback 1000. The system runs gentoo on a Geode LX processor.
I originally switched from screen to tmux because screen has problems with terminals larger than 256 chars in width. Maybe there are patches around, but I couldn't find a solution back then (I don't think they solved it until now?). Anyway, tmux works find with >256 char wide terminals . And soon I realized how much "better" tmux is.
nice seeing you switching to tmux too
The equivalent of -x is the default with tmux unless you explicitly tell it to detach other sessions. You can also create a grouped session with "tmux new -t othersession" if you want them to have different a current window.
All of the stuff at that link is possible in tmux and is often much easier�
[Sep 15, 2009] The Many Uses of Screen By Juliet Kemp
[Jul 11, 2009] Screen (vim + gnu screen) - Start gnu screen w- your vim session and a split shell + send commands to the sh vim online
[Jul 8, 2009] Useful Tricks With Screen
[Jul 7, 2009] tmux 0.9
tmux is a "terminal multiplexer". It allows a number of terminals (or windows) to be accessed and controlled from a single terminal. It is intended to be a simple, modern, BSD-licensed alternative to programs. such as GNU screen
Red Hat Magazine A guide to GNU Screen
Customizing the configuration file
Screen keeps its configuration file in the same vein that many applications do: in a dot file in your user's home directory. This file is aptly named .screenrc. In my experience, most people use
- Make a hardstatus line. This is basically a line at the bottom of the screen that lists your current terminal and all opened ones. It can also display the system clock and the hostname.
- Default screens on startup. It's quite nice to have your IRC connection, mail client, and default SSH connections auto-start for you!
[June 1, 2009] Screen � Manages multiple sessions on one terminal Ubuntu Geek
Using Screen
From your ssh login prompt enter the following command
screen
and select your profile option.
-S sessionname � When creating a new session, this option can be used to specify a meaningful name for the session. This name identifies the session for "screen -list" and "screen -r" actions.
Customise Screen-profiles
If you look in the bottom right corner you'll see there's an "F9 Menu" you can press F9 to reconfigure your screen profiles. Once it opens you should see similar to the following screen here you can see list of changes you can do
Sample screenshots for screen-profile options
[Feb 12, 2004] Curiosity is bliss Essential utility screen
Читайте также: