Как выйти из tty linux

how to kill the tty in unix

Under column the Tty pts/0 and pts/5 are the current active terminals. Apart from those two pts/6 , pts/9 and pts/10 are also present and I had logged into these last week. But the idle time for them is showing as «-» (not idle). How can I kill these 6,9 and 10 terminals?

10 Answers 10

ps -ft pts/6 -t pts/9 -t pts/10 

This would produce an output similar to:

UID PID PPID C STIME TTY TIME CMD Vidya 772 2701 0 15:26 pts/6 00:00:00 bash Vidya 773 2701 0 16:26 pts/9 00:00:00 bash Vidya 774 2701 0 17:26 pts/10 00:00:00 bash 

Grab the PID from the result.

Use the PIDs to kill the processes:

If the process doesn’t gracefully terminate, just as a last option you can forcefully kill by sending a SIGKILL

ps -ft is working for pts/5 but not working to kill pts/6 or pts/9 or pts/10. Throwing error for tty 6,9,10: ERROR: TTY could not be found

Were you able to get the pids for pts 6,9 and 10 ? What is the error reported by the kill command ? Also were there multiple processes listed in the ps output for the same pts ?

ps -ef | grep pts, when I execute this cmd the tty’s 6,9 and 10 are not listed. these 3 tty’s are coming only in «finger» cmd.

finger , who , w and other similar utilites pick up the information from /var/run/utmp which looks like it might have not been updated correctly when those sessions were closed. Since you confirmed that those sessions are not listed in the output of ps , those sessions are closed.

I had the same question as you but I wanted to kill the gnome terminal which I was in. I read the manual on «who» and found that you can list all of the sessions logged into your computer with the ‘-a’ option and then the ‘-l’ option prints the system login processes.

What who gave me

You should get something like this. Then all you have to do is kill the process with the ‘kill’ command.

-n where n is larger than 1. All processes in process group n are signaled. When an argument of the form ‘-n’ is given, and it is meant to denote a process group, either the signal must be specified first, or the argument must be preceded by a ‘—‘ option, otherwise it will be taken as the signal to send. — linux.die.net/man/1/kill

Note: -a switch also prints dead processes. so if your trying to figure out who is using all those tty. they aren’t

kill $(who -la | grep old | awk -F’ +’ ‘‘) worked for me nicely — not sure is safe tho 🙂

Please try pkill -HUP before resorting to pkill -9 (or kill -9 ). This is often all you need to terminate a tty/pty process, and HUP («hangup») still gives the child processes of the terminal a chance to clean up after themselves—cleaning up temporary files, for example.

skill -KILL -v pts/6 skill -KILL -v pts/9 skill -KILL -v pts/10 

From the manpage: These tools are probably obsolete and unportable. The command syntax is poorly defined. Consider using the killall, pkill, and pgrep commands instead.

Читайте также:  Linux compile cpp files

The simplest way is with the pkill command. In your case:

pkill -9 -t pts/6 pkill -9 -t pts/9 pkill -9 -t pts/10 

Regarding tty sessions, the commands below are always useful:

w — shows active terminal sessions

tty — shows your current terminal session (so you won’t close it by accident)

last | grep logged — shows currently logged users

Sometimes we want to close all sessions of an idle user (ie. when connections are lost abruptly).

pkill -u username — kills all sessions of ‘username’ user.

And sometimes when we want to kill all our own sessions except the current one, so I made a script for it. There are some cosmetics and some interactivity (to avoid accidental running on the script).

#!/bin/bash MYUSER=`whoami` MYSESSION=`tty | cut -d"/" -f3-` OTHERSESSIONS=`w $MYUSER | grep "^$MYUSER" | grep -v "$MYSESSION" | cut -d" " -f2` printf "\e[33mCurrent session\e[0m: $MYUSER[$MYSESSION]\n" if [[ ! -z $OTHERSESSIONS ]]; then printf "\e[33mOther sessions:\e[0m\n" w $MYUSER | egrep "LOGIN@|^$MYUSER" | grep -v "$MYSESSION" | column -t echo ---------- read -p "Do you want to force close all your other sessions? [Y]Yes/[N]No: " answer answer=`echo $answer | tr A-Z a-z` confirm=("y" "yes") if [[ "$" =~ "$answer" ]]; then for SESSION in $OTHERSESSIONS do pkill -9 -t $SESSION echo Session $SESSION closed. done fi else echo "There are no other sessions for the user '$MYUSER'". fi 

Источник

How to close a tty

I’ve opened several ttys and I don’t know the key combination to use to close a tty. I’m using Arch Linux.

You didn’t open them, they’re open. You just changed VT. If you want to log out from one of them, use exit . If you are not logged in, don’t worry. It was there before, just you weren’t looking at it.

@goldilocks, VTs can be dynamically allocated and closed. The first one is always allocated when the console is on it, init and X generally allocate the next ones, but you can allocate more. Opening the /dev/ttyx device is enough to allocate it.

@StephaneChazelas : Fair enough. I was just inferring from «using key combinations» that ngwdaniel actually did not start anything that init hadn’t spawned already. If so, there’s no need to close those (and as you point out in your answer, that’s not so easily done anyway).

@goldilocks thank you, this is the answer I was looking for. I’m a silly beginner and I thought it was me who opened the ttys by + etc

2 Answers 2

«Closing» a TTY

  • If systemd is not the init being used then this will not help you.
  • sysvinit is no longer supported by Arch Linux

systemd ‘s systemctl is used to control all the service units on the system. To learn more about it reference man systemd.unit . Stopping the getty service on the desired tty will perform the task in question. Below is the command to perform this action and I’ve also added a test so you can comfirm the results.

# systemctl stop getty@ttyX.service

  • Replace X with the tty number you would like to close
    • If [F4] was used to switch to the tty then the service is named getty@tty4.service .

    Test

    1. Switch to tty4 and enter your username and password .
      • ++[F4]
    2. Launch your favorite text editor
      • vim foo.bar
    3. Switch back to tty1 or whichever tty you were originally in
      • ++[F1]
    4. Open a terminal window and check if vim is running
      • pgrep vim
        • pgrep returns the signal process number of the specified application. Multiple numbers will be returned if there are multiple instances of the same application
          • (if there are four terminal windows open then pgrep will output four process numbers)
    5. As root stop the getty service for tty4
      • # systemctl stop getty@tty4.service
    6. Recheck if vim is still active on tty4 where it was opened and editing foo.bar
      • pgrep vim (if there is no output/less output than in step 4, then there is no process)
    7. Double check the status of the getty@.service for tty4
      • systemctl status getty@tty4.service | grep -i «Active»
        • Piping the output to grep -i «Active» will only output the required line that you’ll need to observe to confirm the getty has been disabled
          • Active: inactive (dead)

    Источник

    Как переключаться между TTY без использования функциональных клавиш в Linux

    В этом кратком руководстве описывается, как переключаться между TTY без функциональных клавиш в Unix-подобных операционных системах.

    Прежде чем идти дальше, мы посмотрим, что такое TTY.

    Как упоминалось в ответе на форуме AskUbuntu, слово TTY появилось из TeleTYpewriter.

    Еще в ранние дни Unix пользовательские терминалы, подключенные к компьютерам, были электромеханическими телепринтерами или телетайпами (tty вкратце).

    С тех пор имя TTY продолжает использоваться для консолей с текстом. В настоящее время все текстовые консоли представляют собой виртуальные консоли, а не физические консоли. Команда TTY печатает имя файла терминала, подключенного к стандартному входу.

    Переключение между TTY в Linux

    По умолчанию в Linux есть 7 tty.

    Они известны как tty1, tty2 … .. tty7.

    От 1 до 6 tty – только командная строка.

    7th tty – графический интерфейс (ваш рабочий стол X).

    Вы можете переключаться между различными TTY, используя клавиши CTRL + ALT + Fn.

    Например, чтобы переключиться на tty1, мы набираем CTRL + ALT + F1.

    Вот как выглядит tty1 на сервере Ubuntu 18.04 LTS.

    Если ваша система не имеет сеанса X, просто введите Alt + Fn. Вам не нужно использовать CTRL.

    В некоторых версиях Linux (например, с Ubuntu 17.10 и далее) на экране входа в систему теперь используется виртуальная консоль 1.

    Таким образом, вам нужно нажать CTRL + ALT + F3 до CTRL + ALT + F6 для доступа к виртуальным консолям.

    Чтобы вернуться в среду рабочего стола, нажмите CTRL + ALT + F2 или CTRL + ALT + F7 на Ubuntu 17.10 и более поздних версиях.

    До сих пор мы видели, что мы можем легко переключаться между TTY, используя CTRL + ALT + Function_Key (F1-F7).

    Однако, если вы не хотите использовать клавиши функций по какой-либо причине, в Linux есть простая команда с именем chvt.

    chvt описание

    Команда «chvt N» позволяет вам переключиться на терминал N переднего плана, так же, как нажать CTRL + ALT + Fn.

    Соответствующий экран создается, если он еще не существует.

    Посмотрим, напечатаем ли система текущий tty:

    Пример вывода с моего сервера Ubuntu 18.04 LTS.

    Теперь перейдем к tty2. Для этого введите:

    Помните, что вам нужно использовать «sudo» с командой chvt.

    Теперь проверьте текущий tty с помощью команды:

    Вы увидите, что tty теперь изменился.

    Аналогичным образом, вы можете переключиться на tty3, используя «sudo chvt 3», tty4, используя «sudo chvt 4» и так далее.

    Команда Chvt может быть полезна, когда какая-либо из ваших функциональных клавиш не работает.

    Чтобы просмотреть общее количество активных виртуальных консолей, запустите:

    $ fgconsole 2

    Как вы можете видеть, в моей системе есть два активных VT.

    Вы можете увидеть следующий нераспределенный виртуальный терминал, используя команду:

    $ fgconsole --next-available 3

    Виртуальная консоль не используется, если она не является консолью переднего плана, и никакой процесс не открывается для чтения или записи, и на ее экране не было выделено текста.

    Чтобы избавиться от неиспользуемых VT, просто введите:

    Вышеупомянутая команда освобождает память ядра и структуры данных для всех неиспользуемых виртуальных консолей.

    Чтобы сказать проще, эта команда освободит все ресурсы, связанные с неиспользуемыми виртуальными консолями.

    Для получения дополнительной информации см. Справочные страницы соответствующей команды.

    Источник

    Linux Mint Forums

    Forum rules
    There are no such things as «stupid» questions. However if you think your question is a bit stupid, then this is the right place for you to post it. Please stick to easy to-the-point questions that you feel people can answer fast. For long and complicated questions prefer the other forums within the support section.
    Before you post please read how to get help. Topics in this forum are automatically closed 6 months after creation.

    How do I exit a tty terminal ?

    Post by gg22LM » Mon Mar 13, 2017 7:23 am

    By mistake I entered CNTL-ALT-F1 and got a tty1

    I could login , but I could not exit or return to the GUI

    I had to reboot the PC, since I could not escape

    Does anyone know what to do ?
    I have read somewhere that cntl-alt-F7 should do the trick, but it only opens another tty

    Thank you in advance for your help

    Re: Hoe do I exit a tty terminal ?

    Post by Cosmo. » Mon Mar 13, 2017 7:34 am

    To log out in a terminal or virtual console press ctrl-d.
    To return to the graphical environment from a virtual console press either ctrl-alt-F7 or ctrl-alt-F8 (which one works is not foreseeable). If you are in tty1 you can also use alt-left, from tty6 you can use alt-right.

    • Important Notices
    • ↳ Rules & Notices
    • ↳ Releases & Announcements
    • ↳ Main Edition Support
    • ↳ Beginner Questions
    • ↳ Installation & Boot
    • ↳ Software & Applications
    • ↳ Hardware Support
    • ↳ Graphics Cards & Monitors
    • ↳ Printers & Scanners
    • ↳ Storage
    • ↳ Sound
    • ↳ Networking
    • ↳ Virtual Machines
    • ↳ Desktop & Window Managers
    • ↳ Cinnamon
    • ↳ MATE
    • ↳ Xfce
    • ↳ Other topics
    • ↳ Non-technical Questions
    • ↳ Tutorials
    • Debian Edition Support
    • ↳ LMDE Forums
    • ↳ Beginner Questions
    • ↳ Installation & Boot
    • ↳ Software & Applications
    • ↳ Hardware Support
    • ↳ Networking
    • ↳ Tutorials
    • ↳ Other Topics & Open Discussion
    • ↳ LMDE Archive
    • Interests
    • ↳ Gaming
    • ↳ Scripts & Bash
    • ↳ Programming & Development
    • Customization
    • ↳ Themes, Icons & Wallpaper
    • ↳ Compiz, Conky, Docks & Widgets
    • ↳ Screenshots
    • ↳ Your Artwork
    • Chat
    • ↳ Introduce Yourself
    • ↳ Chat about Linux Mint
    • ↳ Chat about Linux
    • ↳ Open Chat
    • ↳ Suggestions & Feedback
    • International
    • ↳ Translations
    • ↳ Deutsch — German
    • ↳ Español — Spanish
    • ↳ Français — French
    • ↳ Italiano — Italian
    • ↳ Nederlands — Dutch
    • ↳ Português — Portuguese
    • ↳ Русский — Russian
    • ↳ Suomi — Finnish
    • ↳ Other Languages
    • ↳ Čeština-Slovenčina — Czech-Slovak
    • ↳ Magyar — Hungarian
    • ↳ 日本語 — Japanese
    • ↳ Polski — Polish
    • ↳ Svenska — Swedish
    • ↳ Українська — Ukrainian

    Powered by phpBB® Forum Software © phpBB Limited

    Источник

Оцените статью
Adblock
detector