пятница, 26 февраля 2010 г.

LPI exam 101 prep: The X Window System

В рамках подготовки к сдаче экзамена 101 уровня Junior Level Linux Professional LPIC-1 публикую краткие описания команд и фактов из подготовительных материалов IBM к этому экзамену.

Install and configure X


The X Window System, also known simply as X or X11, is a window system for
graphical (bitmap) displays. X originated at MIT in 1984.

The original configuration tool, xf86config, required a user to have and enter detailed
information about video card and monitor timings. Recent versions of XFree86 are
capable of dynamically determining the available hardware and can run with little or
no configuration information.

XFree86 -autoconfig
Running XFree86 with the -autoconfig option will attempt to automatically
configure the X server.

XFree86 -configure
Running XFree86 with the -configure option may work if the -autoconfig
option does not.

xf86cfg
The xf86cfg command attempts to start the display and input drivers.

xf86config
The xf86config command uses a text-mode interface to interactively prompt
for information about your mouse, keyboard, video card, and display.

The configuration file is named xorg.conf rather than XF86Config. You may find it in
one of several places: /etc/xorg.conf, /etc/X11/xorg.conf, /usr/X11R6/etc/xorg.conf,
/usr/X11R6/lib/X11/xorg.conf.hostname, or /usr/X11R6/lib/X11/xorg.conf.

X -configure
Running X with the -configure option causes the X server to load each
driver module, probe for the driver, and create a configuration file that is saved
in the home directory of the user who started the server (usually /root). The file
is called xorg.conf.new.
xorgcfg
This tool is similar to xf86cfg
xorg86config
The xorgconfig command uses a text-mode interface to interactively prompt
for information about your mouse, keyboard, video card, and display. As with
xf86config, you will need horizontal and vertical frequency information for your
display. You can select most video cards from a database of known video
cards. If not, you may need specific chipset and timing information for your
card.

use the xvidtune command to tune the size and position of your X display.

With the core X11 fonts system, the X Server obtains fonts and font information from
a font server. The X font server, xfs, usually runs as a daemon and is started at
system startup, although it is possible to run it as an ordinary task.

You can use the xdpyinfo command to check your X server.

The Xft library provides functions that allow client applications to select fonts based
on pattern criteria and to generate glyphs to send to the server.

the mkfontdir command created the fonts.dir file.
When installing scalable fonts, such as TrueType or Type1 fonts, an extra step is
required to create scaling information. After you copy the font files to the target
directory, run the mkfontscale command and then the mkfontdir command.
The mkfontscale command will create an index of scalable font files in a file called
fonts.scale.

Set up a display manager

The initialization scripts (/etc/init.d/boot or /etc/init.d/rcS) will then run other scripts.
Eventually, a series of scripts for the chosen runlevel will be run. For the above
examples, these might include /etc/rc2.d/S13gdm (Ubuntu) or
/etc/init.d/rc5.d/S16xdm (SUSE), which are both scripts to run a display manager.
You will find that the rcn.d directories in /etc/init.d usually contain symbolic links to
scripts in /etc/init.d without the leading S (or K) and number. The S indicates that the
script should be run when the runlevel is entered, and the K indicates that the script
should be run when the runlevel is terminated. The digits specify an order from 1 to
99 in which the scripts should be run.

You may find that the script for running a display manager, say
/etc/init.d/rc5.d/S16xdm, may be a small script that contains additional logic to
determine which display manager will really be run.

It should come as no surprise that you can control whether your display manager is
started at system startup simply by creating symbolic links for starting and stopping it
in the appropriate rcn.d directory.

The X Display Manager (XDM) is included in the XFree86 and X.Org packages.
Under the Filesystem Hierarchy Standard, the configuration files should be located
in /etc/X11/xdm. The main configuration file is /etc/X11/xdm/xdm-config. This file
contains the location of other files used by XDM, information on authorization
requirements, the names of scripts run to

KDM is the K Desktop Manager for the K Desktop Environment (KDE). KDE version
3 uses a kdmrc configuration file, a change from earlier versions, which used
configuration information that was based on the xdm configuration files. This is
located in the $KDEDIR/share/config/kdm/ directory, where $KDEDIR might be
/etc/kde3/kdm/ or perhaps somewhere else. For example, on a SUSE SLES8
system, this is located in /etc/opt/kde3/share/config/kdm.

You can also change many of the
Login Manager settings by using the KDE control center (kcontrol)

GDM is the GNOME Desktop Manager for the GNOME Desktop Environment. This
desktop manager was not based on XDM, but was written from scratch. GDM uses a
gdm.conf configuration file, normally located in the /etc/X11/gdm directory.

You can configure GDM by editing the gdm.conf file. You can also change many of
the settings by using the gdmsetup command.

Customize a window manager

Configuration files for startx and xinit
File Description
$HOME/.xinitrc User-defined executable script that
merges in resource files and starts
client applications
$HOME/.xserverrc User-defined executable script that
provides overrides for default X

/usr/X11R6/lib/X11/xinit/xinitrc System default executable script
that merges in resource files and
starts client applications
/usr/X11R6/lib/X11/xinit/xserverrc System default executable script
that provides overrides for default X
server configuration
$HOME/.Xresources User-defined file describing
resources for X applications
$HOME/.Xmodmap User-defined file defining keyboard
and mouse settings
/usr/X11R6/lib/X11/xinit/.Xresources System default file describing
resources for X applications
/usr/X11R6/lib/X11/xinit/.Xmodmap System default file defining
keyboard and mouse settings

Since there are many attributes, it is
easier to have defaults. Such defaults are stored in a resource database, which is
built from resource files using the xrdb command.

Several tools can help you customize windows and keystrokes.
xrdb
Merges resources from a resource file into the X resource database for the running X server. By default it passes the source resource file through a C++
compiler. Specify the -nocpp option if you do not have a compiler installed.
xmodmap
Sets keyboard and mouse bindings. For example, you can switch settings for
left-handed mouse usage, or set up the backspace and delete keys to work the
way you are accustomed to.
xwininfo
Tells you information about a window, including geometry information.
editres
Lets you customize the resources for windows on your screen, see the
changes, and save them in a file that you can later use with xrdb.
xev
Starts a window and captures X events that are displayed in the originating
xterm window. Use this to help determine the appropriate codes to use when
customizing keyboards or checking mouse events.

An X display is known by a name of the form
hostname:displaynumber.screennumber. For Linux running on a workstation such as
a PC, there is typically only one display with a single screen. In this case, the
displayname may be, and usually is, omitted so the display is known as :0.0.

For local displays on Linux systems, authorization usually depends on a so-called
MIT-MAGIC-COOKIE-1, which is usually regenerated every time the X server
restarts. A user can extract the magic cookie from the .Xauthority file in his or her
home directory (using the xauth extract command and give it to another user to
merge into that user's .Xauthority file using the xauth merge command.
Alternatively, a user can grant authority for other users to access the local system
using the xhost +local: command.

To give all local users authority to open applications on the display (:0.0), user ian
can use the xhost command. Open a terminal window on your desktop and enter
this command:
xhost +local:
Note the trailing colon (:). This will allow other users on the same system to connect
to the X server and open windows. Since you are a single-user system, this means
that you can su to an arbitrary non-root user and can now launch xclock or other X
applications.

вторник, 16 февраля 2010 г.

Основы использования редактора VI


Текстовый консольный редактор VI встроен во все Unix-системы и ему около 40 лет. Это серьезный возраст, и он ему соответствует. Нет повода, чтобы не написать пару строк об этом замечательном явлении.

Человек из мира Windows встает в продолжительный ступор оказавшись в консоли этого редактора. И, обычно, закрывает его. И забывает, открыв для себя с радостью Pico, Nano, etc.

Но все равно, рано или поздно, вы с ним сталкиваетесь. От VI не уйти ;-). Поэтому опишу основные команды для работы в этом редакторе и приведу ссылки на тематические ресурсы.

Основы основ

Чтобы открыть для редактирования уже существующий файл, путь к этому файлу нужно указать в качестве параметра: "vi путь_к_файлу".

Пока буфер не заполнен текстом, в начале каждой строки экрана отображается символ "~", обозначающий, что в этом месте буфера нет ничего, даже пустой строки.

Кстати, у vi, конечно же, есть конфигурационный файл. Он называется .exrc и находится в домашнем каталоге.

Наконец, чтобы ввести текст, нужно перейти из командного режима в режим вставки, нажав клавишу "i".

Например, по командам "O" и "o" ("open") можно вводить текст с новой строки (до или после текущей), по команде "I" – с начала строки, команды "a" и "A" ("append") ведают добавлением символов (после курсора или в конец строки) и т. п.

Передвинуть курсор на начало текущей строки можно командой "0", на первый непробельный символ в строке – "^", в конец строки – "$".


Абзацами Vi считает фрагменты текста, разделенные пустой строкой, к началу предыдущего/следующего абзаца можно попасть командами "{" и "}" соответственно. Очень распространенная задача – необходимость попасть в самый конец файла: для этого служит команда "G" ("Go"), в самое начало – "gg".

Часто используемые команды

* :q — выход
* :q! — выход без сохранения файла
* :w — сохранить файл на диске
* :wq — выход с сохранением файла
* :e! — перезагрузить текущий файл
* :33 — перепрыгнуть на 33ю строку текстового файла
* i — перейти в режим редактирования
* u — отменить последнее действие
* x — удалить символ под курсором
* dd — удалить всю строку
* /qso — найти слово qso в тексте после курсора
* Esc → :wq → Enter — выйти из файла, сохранив его;
* Esc → :q! → Enter — выйти из файла, не сохранив его.

Чтобы получить подробную помощь по редактору vi, выполните команду man vi в Unix shell (q — выход из справки).

Основные команды vi

vi filename Вызов редактора vi для редактирования файла filename
a Добавить текст после курсора (переход в режим ввода)
Перейти из режима ввода в командный режим
h Переместить курсор на один символ влево
j Переместить курсор вниз на одну строку
k Переместить курсор вверх на одну строку
l Переместить курсор на один символ вправо
x Удалить символ

:w Записать в файл
:q Завершить работу с vi
:q! Завершить работу с vi без сохранения файла
:wq Записать буфер в файл и завершить работу с vi
ZZ Записать буфер в файл и завершить работу с vi

Позиционирование курсора

h Переместить курсор на один символ влево
j Переместить курсор вниз на одну строку
k Переместить курсор вверх на одну строку
l Переместить курсор на один символ вправо
$ Переместить курсор на последний символ в строке
0(ноль) Переместить курсор на первый символ в строке
^ Переместить курсор на первый не пустой символ в строке

w Переместить курсор к началу следующего слова
W Переместить курсор к началу следующего слова, не учитывая все знаки пунктуации

1G Перейти к первой строке в файле
G Перейти к последней строке в файле
nG Перейти к строке номер n в файле
:set num Показывать номера строк в файле
:set nonum Не показывать номера строк в файле

^f Прокрутить экран вперёд на полное окно.
^b Прокрутить экран назад на полное окно.

Поиск и замена текста по шаблону (*)

/pattern Поиск вперёд в буфере до первого появления шаблона pattern.
?pattern Поиск назад в буфере до первого появления шаблона pattern.
n Повторить последнюю команду поиска

:s/pattern/new_text/ Заменить первое появление шаблона pattern в текущей строке на new_text
:s/pattern/new_text/g Заменить каждое появление шаблона pattern в текущей строке на new_text
:g/pattern/s//new_text/g Заменить каждое появление шаблона pattern в файле на new_text

* В шаблоне (pattern) работают регулярные выражения (RE - Regular Expressions). Подробнее про регулярные выражения можно найти в IBM AIX InfoCenter.

Ввод, удаление и замена текста

a Создать текст после курсора (переход в режим ввода)
A Создать текст в конце текущей строки (переход в режим ввода)
i Создать текст перед курсором (переход в режим ввода)

o Вставить новвую строку ниже текущей строки и перейти в неё (переход в режим ввода)
O Вставить новвую строку выше текущей строки и перейти в неё (переход в режим ввода)

В режиме ввода: удалить текущий символ
x Удалить текущий символ
dw Удалить слово над курсором (текст помещается во временный буфер)
dW Удалить слово и пунктуацию над курсором (текст помещается во временный буфер)
dd Удалить текущую строку (текст помещается во временный буфер)
rx Заменить текущий символ на символ x
R Перейти в режим ввода с заменой текста


Дополнительные команды

u Отменить последнюю команду
. Повторить последнюю команду
j Соединить текущую строку со строкой, расположенной ниже
yy Скопировать строку во временный буфер
p Поместить содержимое временного буфера, полученное с помощью команды y или команд удаления, в текст после курсора
:show mode Показывать режим работы vi в строке статуса (командный или ввода)


Работа с файлами и выход из редактора

ZZ Записать текст в файл и завершить работу с vi
:wq Записать текст в файл и завершить работу с vi
:w Записать текст в файл
:w! Записать текст в файл, даже при недостатке прав доступа (если вы владелец файла или root)
:q Завершить работу с vi без записи текст в файл, если буфер не изменялся
:q! Завершить работу с vi без записи текст в файл, даже если текст изменялся
:w filename Записать текст в новый файл filename
:w! filename Перезаписать содержимое текста в уже существующий файл filename

Отечественные ресурсы по теме VI

http://www.intuit.ru/department/os/linux/9/
http://www.aixportal.ru/content/view/23/139/
http://ru.wikipedia.org/wiki/Vi

VIM

http://www.vim.org/