- How to close the Terminal?
- 3 Answers 3
- How to close terminal with my program?
- 1 Answer 1
- Как убить процесс Linux
- Как происходит завершение процесса?
- Как убить процесс Linux?
- Как завершить процесс с помощью pkill
- Как остановить процесс с помощью killall
- Выводы
- Close Terminal window from within shell script (Unix)?
- 6 Answers 6
- How to really clear the terminal?
- 12 Answers 12
- Explanation
How to close the Terminal?
I found many questions about how to open the terminal but cant find a question with an answer on how to close the terminal and return back to the desktop of Ubuntu (note: I am on virtual machine)
3 Answers 3
You can type exit . You can type ctrl — d . Or (if you’re on a virtual terminal), you use ctrl — alt — F8 .
ctrl + shift + w closes the current tab and ctrl + shift + q closes the entire window.
This is similar to other commands that also are normally ctrl + whatever such as, ctrl + c and ctrl + v for copy and paste which, in gnome-terminal are, ctrl + shift + c and ctrl + shift + v respectively.
I’m not sure if the following works in a virtual machine, however, it is important to also note that when you switch to a tty text session such as tty1 — tty6 using ctrl + alt + f1 up to ctrl + alt + f6 , you can return to the regular desktop xsession by pressing ctrl + alt + f7 typically or sometimes ctrl + alt + f8 .
TL;DR: Press Alt + F7 .
You are apparently asking how to close a virtual console, also known as a virtual terminal—a full-screen text terminal you got to by pressing a key combination like Ctrl + Alt + F1 , Ctrl + Alt + F2 , and so forth.
In infer this since you say you wish to «return back to the desktop of Ubuntu» (indicating you are not on your desktop now) and, in a comment, wrote:
my terminal in virtual machine is at a black background and when i type exit it refreshes its not a program .
Rather than actually closing your text-based virtual console, you probably just want to get back to the virtual console on which the graphical user interface is running. This is usually the seventh virtual console, so press Alt + F7 . ( Ctrl is optional when switching from a virtual console that does not have the GUI running on it; however, you must use it when switching from a virtual console that does have the GUI running on it.)
If those key combinations do not work—or change the virtual console of the host rather than the guest—and your Ubuntu system is a VirtualBox guest system, see How do I switch between virtual terminals in a guest system? as suggested by LiveWireBT.
Another way, which is much less often used, is to run the command chvt 7 .
Источник
How to close terminal with my program?
The problem is that my program do the scan, but the terminal remains open, i compile and run my program with termianl using: gcc auto.cpp -o auto.exe to compile, and ./auto.exe to run. I try to use system(«exit») but it doesn’t work. P.S. sorry for my bad english.
1 Answer 1
Although you can not make your compiled application close the terminal window in which it is running, it is easy to make this happen by changing the way how you execute your program.
For example, if your executable application can be started using ./myprogramm , you could just type the command below in your terminal to first run myprogramm and as soon as it finishes, run the exit command to close the shell and with it the whole terminal window:
Or maybe it would be even better to only close the terminal window if your application exited successfully, without any error (indicated by an exit status code other than 0). You can use && instead of ; to run the second command only if the first command was successful:
A third alternative would be to replace the shell running in your terminal window with your application, instead of running your application inside the shell. That way, the terminal window will close as soon as your application exits and you don’t have to exit the shell at that point any more:
One big difference between the first two approaches ( ; exit and && exit ) and the last one using exec is, that in the first case, you can kill the command you ran by hitting Ctrl + C and you will be back in the shell, the window will stay open. If you used exec , this will also kill your application, but as there is no more shell inside which it is running, the terminal window will close immediately as well.
Источник
Как убить процесс Linux
Несмотря на то что Linux стабильнее чем Windows, в плане работы программ и различных сервисов, случается всякое и иногда возникает необходимость завершить процесс Linux. Это может понадобиться, если программа завила, когда вы запустили системный сервис в фоне через терминал, а не систему инициализации, а также во многих других случаях, когда убить процесс Linux проще, чем перезагружать всю систему.
В этой статье мы рассмотрим несколько самых распространенных способов завершить процесс Linux. Опишем подробно как происходит остановка процесса и как все сделать правильно.
Как происходит завершение процесса?
Управление процессами в операционной системе Linux осуществляется с помощью сигналов. В том числе и завершение любого процесса. Сигналы передает система, но также их может передавать пользователь с помощью специальных команд или даже сочетаний клавиш в терминале. Когда процессу приходит сигнал о необходимости завершиться, он должен выполнить некоторые подготовительные действия.
Необходимо завершить дочерние процессы, удалить временные файлы, сокеты и так далее. Но в зависимости от сложности ситуации процесс может реагировать не на все сигналы. Рассмотрим основные сигналы, которые используются для завершения процесса:
- SIGINT — самый безобидный сигнал завершения, означает Interrupt. Он отправляется процессу, запущенному из терминала с помощью сочетания клавиш Ctrl+C. Процесс правильно завершает все свои действия и возвращает управление;
- SIGQUIT — это еще один сигнал, который отправляется с помощью сочетания клавиш, программе, запущенной в терминале. Он сообщает ей что нужно завершиться и программа может выполнить корректное завершение или проигнорировать сигнал. В отличие от предыдущего, она генерирует дамп памяти. Сочетание клавиш Ctrl+/;
- SIGHUP — сообщает процессу, что соединение с управляющим терминалом разорвано, отправляется, в основном, системой при разрыве соединения с интернетом;
- SIGTERM — немедленно завершает процесс, но обрабатывается программой, поэтому позволяет ей завершить дочерние процессы и освободить все ресурсы;
- SIGKILL — тоже немедленно завершает процесс, но, в отличие от предыдущего варианта, он не передается самому процессу, а обрабатывается ядром. Поэтому ресурсы и дочерние процессы остаются запущенными.
Важно понимать, что нужно дать процессу возможность завершиться корректно. Желательно, чтобы порты и сокеты были освобождены, закрыты и удаленны временные файлы. Поэтому никогда не передавайте сразу SIGKILL. Передавайте сигналы завершения в последовательности, как они перечислены выше.
Сначала Ctrl+C, если это возможно, затем SIGTERM — он хоть и завершает процесс, но делает эту культурно, и только в крайнем случае SIGKILL. А теперь рассмотрим как убить процесс по pid Linux на практике. Если вы всегда используете SIGKILL, тогда на ум приходит такая картинка:
Как убить процесс Linux?
Для передачи сигналов процессам в Linux используется утилита kill. Ее синтаксис очень прост:
$ kill -сигнал pid_процесса
Сигнал представляет собой один из выше перечисленных сигналов для завершения процесса. По умолчанию, если этот параметр не указан, используется сигнал SIGTERM, что является очень правильно. Также нам нужно указать какой процесс нужно завершить. Для этого используется уникальный идентификатор процесса — PID.
Допустим, у нас выполняется утилита ping. Мы хотим ее завершить с помощью kill. Тогда, сначала мы узнаем ее идентификатор с помощью команды ps:
ps aux | grep ping
В первой строчке отобразится сама утилита ping, а во второй сама программа ps. Берем нужный PID и завершаем процесс с помощью SIGTERM:
kill -TERM 20446
И только если после этой команды процесс продолжил висеть, а это вы можете проверить, выполнив ps. Только теперь можно выполнить SIGKILL:
kill -KILL 20446
Теперь снова проверяем:
Если процесс запущен от суперпользователя, то, естественно, вам нужно использовать sudo. Не всегда удобно уничтожать процесс по его PID, как минимум, потому, что вам этот PID нужно еще узнать. Мы могли бы нагородить сложных конструкций с использованием xargs, чтобы вычислять автоматически pid по имени процесса и сразу же его завершать, но в этом нет необходимости. Уже существуют специальные утилиты.
Как завершить процесс с помощью pkill
Утилита pkill — это оболочка для kill, она ведет себя точно так же, и имеет тот же синтаксис, только в качестве идентификатора процесса ей нужно передать его имя. Утилита сканирует директорию proc и находит PID первого процесса с таким именем, затем отправляет ему SIGTERM. Таким образом, вы можете убить процесс по имени Linux. Например, если мы хотим завершить тот же ping:
Также можно вручную задать тип сигнала:
pkill -TERM ping
Вместо ps, вы можете использовать утилиту pgrep для поиска pid процесса, убедимся что наша программа завершена:
Но если вам программа создала несколько процессов, например, браузер chromium или firefox создают отдельный процесс для каждой из вкладок, то эта утилита мало чем поможет. Тут нужен следующий вариант.
Как остановить процесс с помощью killall
killall работает аналогично двум предыдущим утилитам. Она тоже приминает имя процесса в качестве параметра и ищет его PID в директории /proc. Но эта утилита обнаружит все процессы, с таким именем и завершит их. Например:
Как видите, запущено несколько процессов, осталось остановить процесс Linux с помощью killall:
Команда завершит все запущенные утилиты ping, вы можете убедиться в этом еще раз выполнив pgrep:
Выводы
В этой статье мы рассмотрели как убить процесс Linux. Иногда эта задача может быть очень полезной, но важно понимать, что ее нужно выполнять правильно. Нельзя сказать, что передача SIGKILL вместо SIGTERM очень опасна, но так делать не стоит. Надеюсь, эта информация была полезна для вас.
Источник
Close Terminal window from within shell script (Unix)?
Is there a way to close a Terminal window from within a shell script? I have a .command file that should just get out of the way once it’s done.
6 Answers 6
Using exit 0 will cleanly terminate the script.
Whether Terminal window stays open is user-configurable. The default is to always stay open. To change this:
When «Close if shell exited cleanly» is used, the script will close the window if the exit result is 0, which is the default if nothing went wrong.
Since you don’t want to delete all Terminal windows, first change the name of your window from «Terminal» to something else:
Then at the end of the script, use:
osascript -e ‘tell application «Terminal» to close (every window whose name contains «My Window Name»)’ &
You can use apple script to quit the terminal app . Add the following to your script —
This will give you a popup confirming to close the app. You can disable this in Terminal preferences.
Alternatively, you can also use killall command to quit the app. The following would work just as well.
Just as a side note, you can freely add the above commands to your script and it would work as you want. However, there are few caveats. First being you will limit the ability of your script to work on different boxes. Secondly, it would be safer to use nohup so that any commands that are currently running won’t quit due to quitting of the Terminal app .
This works for me:
This will work for closing just your windows opened with a .command file but leave things already running in other terminal windows. I know that I almost always have either sass or grunt watch something so I don’t want to quit terminal totally.
This will close the Terminal window for your script and keep any other Terminal windows open as long as their window titles don’t match. For it to work Terminal will have to be added to the list of applications permitted to use the Accessibility framework. You can also cycle through Terminal windows with a repeat command and close every window x that contains a UI element «Close» on sheet 1.
I find the best solution for this is to use Automator to create a true OSX application which will work the same way regardless of how your system is configured. You can have the Automator run your shell script, or you can embed the shell script itself in Automator.
Here is how you do it:
- Run Automator (in Applications).
- Choose «New Document» and when it asks «Choose a type for your document» choose «Application»
- In the left panel, select «Utilities» then «Run Shell Script».
- Type in your script commands in the workflow item in the right panel. You can either call another shell script, or just put your commands in their directly.
- Save the Application, which will be a full-fledged Mac App. You can even cut-and-paste icons from other apps to give your script some personality.
Источник
How to really clear the terminal?
I can issue the clear command or press Ctrl + L to clear the current Ubuntu terminal, but this just shifts previous output upwards and if you use mouse scroll or PgUP and PgDown keys it’s hard to distinguish where the output of previous command ends and output of current command begins.
Is there a way to really clear the terminal so I won’t see previous command results?
12 Answers 12
Yes, the command you’re looking for is
In contrast to clear , or Ctrl + L , reset will actually completely re-initialise the terminal, instead of just clearing the screen. However, it won’t re-instantiate the shell (bash). That means that bash’s state is the same as before, just as if you were merely clearing the screen.
As @Ponkadoodle mentions in the comments, this command should do the same thing more quickly:
From the other answers:
You can set a Keyboard Shortcut to reset the terminal, as explained by towolf.
If you’re running Kubuntu, and your terminal is Konsole, you need to go to Edit → Clear history, since reset doesn’t work the same way there, as UncleZeiv notes.
I was looking for this for a while and I found some genius that posted this:
Clears the whole screen buffer, very clean. Works on OS X and believe it works fine on most *nix terminals.
For curious, this part ‘\e[3J’ is a terminal escape command.
/.bashrc and add alias reset=»clear && printf ‘\e[3J'»
You can also assign a shortcut in gnome-terminal by going to Edit → Keyboard Shortcuts. I use Shift + Ctrl + Alt + C .
Cross posting my answer from stackoverflow.
Use the following command to do a clear screen instead of merely adding new lines .
yes that’s a ‘printf’ on the bash prompt.
You will probably want to define an alias though.
Explanation
So this becomes c which is the VT100 escape code for resetting the terminal. Here is some more information on terminal escape codes.
Here are a few other ways of doing it.
The above does not work on the KDE console (called Konsole) but there is hope! Use the following sequence of commands to clear the screen and the scroll-back buffer.
Or perhaps use the following alias on KDE.
I got the scroll-back clearing command from here.
run this command:
This has the same effect as launching a new terminal.
My favorite is printf «\ec» . This can also be printf «\033c» or printf «\x1bc» . That is an ansi escape sequence that miraculously clears the screen and buffer for the terminal output (for most standard terminals I have worked in it seems — I know it works in such as gnome-terminal, terminator, xterm, etc. on Ubuntu-like Linuxes)
I know this works in Linux Mint and Ubuntu 14.04, so I don’t know why people are appending and prepedning things like clear && echo -ne «\033c . printf «\ec» has always worked for me.
Additionally, in my .bashrc I have a binding like this:
Источник