Что такое x сервер в linux
Перейти к содержимому

Что такое x сервер в linux

  • автор:

XSERVER

X is the generic name for the X Window System display server. It is frequently a link or a copy of the appropriate server binary for driving the most frequently used server on a given machine.

STARTING THE SERVER

The X server is usually started from the X Display Manager program xdm(1) or a similar display manager program. This utility is run from the system boot files and takes care of keeping the server running, prompting for usernames and passwords, and starting up the user sessions.

Installations that run more than one window system may need to use the xinit(1) utility instead of a display manager. However, xinit is to be considered a tool for building startup scripts and is not intended for use by end users. Site administrators are strongly urged to use a display manager, or build other interfaces for novice users.

The X server may also be started directly by the user, though this method is usually reserved for testing and is not recommended for normal operation. On some platforms, the user must have special permission to start the X server, often because access to certain devices (e.g. /dev/mouse) is restricted.

When the X server starts up, it typically takes over the display. If you are running on a workstation whose console is the display, you may not be able to log into the console while the server is running.

OPTIONS

Many X servers have device-specific command line options. See the manual pages for the individual servers for more details; a list of server-specific manual pages is provided in the SEE ALSO section below.

All of the X servers accept the command line options described below. Some X servers may have alternative ways of providing the parameters described here, but the values provided via the command line options should override values specified via other mechanisms.
:
displaynumber

The X server runs as the given displaynumber, which by default is 0. If multiple X servers are to run simultaneously on a host, each must have a unique display number. See the DISPLAY NAMES section of the X(7) manual page to learn how to specify which display number clients should try to use.

−a number

sets pointer acceleration (i.e. the ratio of how much is reported to how much the user actually moved the pointer).

disables host-based access control mechanisms. Enables access by any host, and permits any host to modify the access control list. Use with extreme caution. This option exists primarily for running test suites remotely.

−audit level

sets the audit trail level. The default level is 1, meaning only connection rejections are reported. Level 2 additionally reports all successful connections and disconnects. Level 4 enables messages from the SECURITY extension, if present, including generation and revocation of authorizations and violations of the security policy. Level 0 turns off the audit trail. Audit lines are sent as standard error output.

−auth authorization-file

specifies a file which contains a collection of authorization records used to authenticate access. See also the xdm(1) and Xsecurity(7) manual pages.

−background none

Asks the driver not to clear the background on startup, if the driver supports that. May be useful for smooth transition with eg. fbdev driver. For security reasons this is not the default as the screen contents might show a previous user session.

sets the default root window to solid black instead of the standard root weave pattern. This is the default unless -retro or -wr is specified.

disables backing store support on all screens.

turns off key-click.

c volume

sets key-click volume (allowable range: 0-100).

−cc class

sets the visual class for the root window of color screens. The class numbers are as specified in the X protocol. Not obeyed by all servers.

causes the server to generate a core dump on fatal errors.

−deferglyphs whichfonts

specifies the types of fonts for which the server should attempt to use deferred glyph loading. whichfonts can be all (all fonts), none (no fonts), or 16 (16 bit fonts only).

−dpi resolution

sets the resolution for all screens, in dots per inch. To be used when the server cannot determine the screen size(s) from the hardware.

enables DPMS (display power management services), where supported. The default state is platform and configuration specific.

disables DPMS (display power management services). The default state is platform and configuration specific.

−extensionextensionName

disables named extension. If an unknown extension name is specified, a list of accepted extension names is printed.

+extensionextensionName

enables named extension. If an unknown extension name is specified, a list of accepted extension names is printed.

−f volume

sets beep (bell) volume (allowable range: 0-100).

−fc cursorFont

sets default cursor font.

−fn font

sets the default font.

−fp fontPath

sets the search path for fonts. This path is a comma separated list of directories which the X server searches for font databases. See the FONTS section of this manual page for more information and the default list.

prints a usage message.

causes all remaining command line arguments to be ignored.

−maxbigreqsize size

sets the maximum big request to size MB.

disable the display of the pointer cursor.

−nolisten trans-type

disables a transport type. For example, TCP/IP connections can be disabled with −nolisten tcp. This option may be issued multiple times to disable listening to different transport types.

prevents a server reset when the last client connection is closed. This overrides a previous −terminate command line option.

−p minutes

sets screen-saver pattern cycle time in minutes.

permits the server to continue running if it fails to establish all of its well-known sockets (connection points for clients), but establishes at least one. This option is set by default.

causes the server to exit if it fails to establish all of its well-known sockets (connection points for clients).

turns off auto-repeat.

turns on auto-repeat.

starts the stipple with the classic stipple and cursor visible. The default is to start with a black root window, and to suppress display of the cursor until the first time an application calls XDefineCursor(). For the Xorg server, this also sets the default for the DontZap option to FALSE. For kdrive servers, this implies -zap.

−s minutes

sets screen-saver timeout time in minutes.

disables save under support on all screens.

−seat seat

seat to run on. Takes a string identifying a seat in a platform specific syntax. On platforms which support this feature this may be used to limit the server to expose only a specific subset of devices connected to the system.

−t number

sets pointer acceleration threshold in pixels (i.e. after how many pixels pointer acceleration should take effect).

causes the server to terminate at server reset, instead of continuing to run. This overrides a previous −noreset command line option.

−to seconds

sets default connection timeout in seconds.

disables all testing extensions (e.g., XTEST, XTrap, XTestExtension1, RECORD).

ttyxx

ignored, for servers started the ancient way (from init).

sets video-off screen-saver preference.

sets video-on screen-saver preference.

forces the default backing-store of all windows to be WhenMapped. This is a backdoor way of getting backing-store to apply to all windows. Although all mapped windows will have backing store, the backing store attribute value reported by the server for a window will be the last value established by a client. If it has never been set by a client, the server will report the default value, NotUseful. This behavior is required by the X protocol, which allows the server to exceed the client’s backing store expectations but does not provide a way to tell the client that it is doing so.

sets the default root window to solid white instead of the standard root weave pattern.

−x extension

loads the specified extension at init. This is a no-op for most implementations.

enables(+) or disables(-) the XINERAMA extension. The default state is platform and configuration specific.

SERVER DEPENDENT OPTIONS

Some X servers accept the following options:
−ld
kilobytes

sets the data space limit of the server to the specified number of kilobytes. A value of zero makes the data size as large as possible. The default value of −1 leaves the data space limit unchanged.

−lf files

sets the number-of-open-files limit of the server to the specified number. A value of zero makes the limit as large as possible. The default value of −1 leaves the limit unchanged.

−ls kilobytes

sets the stack space limit of the server to the specified number of kilobytes. A value of zero makes the stack size as large as possible. The default value of −1 leaves the stack space limit unchanged.

default|mono|gray|color sets the color allocation policy that will be used by the render extension.

selects the default policy defined for the display depth of the X server.

don’t use any color cell.

use a gray map of 13 color cells for the X render extension.

use a color cube of at most 4*4*4 colors (that is 64 color cells).

disables smart scheduling on platforms that support the smart scheduler.

−schedInterval interval

sets the smart scheduler’s scheduling interval to interval milliseconds.

XDMCP OPTIONS

X servers that support XDMCP have the following options. See the X Display Manager Control Protocol specification for more information.
−query
hostname

enables XDMCP and sends Query packets to the specified hostname.

enable XDMCP and broadcasts BroadcastQuery packets to the network. The first responding display manager will be chosen for the session.

−multicast [address [hop count]]

Enable XDMCP and multicast BroadcastQuery packets to the network. The first responding display manager is chosen for the session. If an address is specified, the multicast is sent to that address. If no address is specified, the multicast is sent to the default XDMCP IPv6 multicast group. If a hop count is specified, it is used as the maximum hop count for the multicast. If no hop count is specified, the multicast is set to a maximum of 1 hop, to prevent the multicast from being routed beyond the local network.

−indirect hostname

enables XDMCP and send IndirectQuery packets to the specified hostname.

−port port-number

uses the specified port-number for XDMCP packets, instead of the default. This option must be specified before any −query, −broadcast, −multicast, or −indirect options.

−from local-address

specifies the local address to connect from (useful if the connecting host has multiple network interfaces). The local-address may be expressed in any form acceptable to the host platform’s gethostbyname(3) implementation.

causes the server to terminate (rather than reset) when the XDMCP session ends.

−class display-class

XDMCP has an additional display qualifier used in resource lookup for display-specific options. This option sets that value, by default it is "MIT-Unspecified" (not a very useful value).

−cookie xdm-auth-bits

When testing XDM-AUTHENTICATION-1, a private key is shared between the server and the manager. This option sets the value of that private data (not that it is very private, being on the command line!).

−displayID display-id

Yet another XDMCP specific value, this one allows the display manager to identify each display so that it can locate the shared key.

XKEYBOARD OPTIONS

X servers that support the XKEYBOARD (a.k.a. "XKB") extension accept the following options. All layout files specified on the command line must be located in the XKB base directory or a subdirectory, and specified as the relative path from the XKB base directory. The default XKB base directory is /usr/lib/X11/xkb.
[+-]accessx
[ timeout [ timeout_mask [ feedback [ options_mask ] ] ] ]

enables(+) or disables(-) AccessX key sequences.

−xkbdir directory

base directory for keyboard layout files. This option is not available for setuid X servers (i.e., when the X server’s real and effective uids are different).

−ardelay milliseconds

sets the autorepeat delay (length of time in milliseconds that a key must be depressed before autorepeat starts).

−arinterval milliseconds

sets the autorepeat interval (length of time in milliseconds that should elapse between autorepeat-generated keystrokes).

−xkbmap filename

loads keyboard description in filename on server startup.

NETWORK CONNECTIONS

The X server supports client connections via a platform-dependent subset of the following transport types: TCPIP, Unix Domain sockets, DECnet, and several varieties of SVR4 local connections. See the DISPLAY NAMES section of the X(7) manual page to learn how to specify which transport type clients should try to use.

GRANTING ACCESS

The X server implements a platform-dependent subset of the following authorization protocols: MIT-MAGIC-COOKIE-1, XDM-AUTHORIZATION-1, XDM-AUTHORIZATION-2, SUN-DES-1, and MIT-KERBEROS-5. See the Xsecurity(7) manual page for information on the operation of these protocols.

Authorization data required by the above protocols is passed to the server in a private file named with the −auth command line option. Each time the server is about to accept the first connection after a reset (or when the server is starting), it reads this file. If this file contains any authorization records, the local host is not automatically allowed access to the server, and only clients which send one of the authorization records contained in the file in the connection setup information will be allowed access. See the Xau manual page for a description of the binary format of this file. See xauth(1) for maintenance of this file, and distribution of its contents to remote hosts.

The X server also uses a host-based access control list for deciding whether or not to accept connections from clients on a particular machine. If no other authorization mechanism is being used, this list initially consists of the host on which the server is running as well as any machines listed in the file /etc/Xn.hosts, where n is the display number of the server. Each line of the file should contain either an Internet hostname (e.g. expo.lcs.mit.edu) or a DECnet hostname in double colon format (e.g. hydra::) or a complete name in the format family:name as described in the xhost(1) manual page. There should be no leading or trailing spaces on any lines. For example:

joesworkstation
corporate.company.com
star::
inet:bigcpu
local:

Users can add or remove hosts from this list and enable or disable access control using the xhost command from the same machine as the server.

If the X FireWall Proxy (xfwp) is being used without a sitepolicy, host-based authorization must be turned on for clients to be able to connect to the X server via the xfwp. If xfwp is run without a configuration file and thus no sitepolicy is defined, if xfwp is using an X server where xhost + has been run to turn off host-based authorization checks, when a client tries to connect to this X server via xfwp, the X server will deny the connection. See xfwp(1) for more information about this proxy.

The X protocol intrinsically does not have any notion of window operation permissions or place any restrictions on what a client can do; if a program can connect to a display, it has full run of the screen. X servers that support the SECURITY extension fare better because clients can be designated untrusted via the authorization they use to connect; see the xauth(1) manual page for details. Restrictions are imposed on untrusted clients that curtail the mischief they can do. See the SECURITY extension specification for a complete list of these restrictions.

Sites that have better authentication and authorization systems might wish to make use of the hooks in the libraries and the server to provide additional security models.

SIGNALS

The X server attaches special meaning to the following signals:

This signal causes the server to close all existing connections, free all resources, and restore all defaults. It is sent by the display manager whenever the main user’s main application (usually an xterm or window manager) exits to force the server to clean up and prepare for the next user.

This signal causes the server to exit cleanly.

This signal is used quite differently from either of the above. When the server starts, it checks to see if it has inherited SIGUSR1 as SIG_IGN instead of the usual SIG_DFL. In this case, the server sends a SIGUSR1 to its parent process after it has set up the various connection schemes. Xdm uses this feature to recognize when connecting to the server is possible.

FONTS

The X server can obtain fonts from directories and/or from font servers. The list of directories and font servers the X server uses when trying to open a font is controlled by the font path.

The default font path is /usr/share/fonts/X11/misc/, /usr/share/fonts/X11/TTF/, /usr/share/fonts/X11/OTF/, /usr/share/fonts/X11/Type1/, /usr/share/fonts/X11/100dpi/, /usr/share/fonts/X11/75dpi/ .

A special kind of directory can be specified using the catalogue: prefix. Directories specified this way can contain symlinks pointing to the real font directories. See the FONTPATH.D section for details.

The font path can be set with the −fp option or by xset(1) after the server has started.

FONTPATH.D

You can specify a special kind of font path in the form catalogue:<dir>. The directory specified after the catalogue: prefix will be scanned for symlinks and each symlink destination will be added as a local fontfile FPE.

The symlink can be suffixed by attributes such as ’unscaled’, which will be passed through to the underlying fontfile FPE. The only exception is the newly introduced ’pri’ attribute, which will be used for ordering the font paths specified by the symlinks.

An example configuration:

75dpi:unscaled:pri=20 −> /usr/share/X11/fonts/75dpi
ghostscript:pri=60 −> /usr/share/fonts/default/ghostscript
misc:unscaled:pri=10 −> /usr/share/X11/fonts/misc
type1:pri=40 −> /usr/share/X11/fonts/Type1
type1:pri=50 −> /usr/share/fonts/default/Type1

This will add /usr/share/X11/fonts/misc as the first FPE with the attribute ‘unscaled’, second FPE will be /usr/share/X11/fonts/75dpi, also with the attribute ’unscaled’ etc. This is functionally equivalent to setting the following font path:

/usr/share/X11/fonts/misc:unscaled,
/usr/share/X11/fonts/75dpi:unscaled,
/usr/share/X11/fonts/Type1,
/usr/share/fonts/default/Type1,
/usr/share/fonts/default/ghostscript

FILES

/etc/Xn.hosts

Initial access control list for display number n

/usr/share/fonts/X11/misc,/usr/share/fonts/X11/75dpi,/usr/share/fonts/X11/100dpi

Bitmap font directories

/usr/share/fonts/X11/TTF,/usr/share/fonts/X11/Type1

Outline font directories

/tmp/.X11-unix/Xn

Unix domain socket for display number n

/usr/adm/Xnmsgs

Error log file for display number n if run from init(8)

/usr/lib/X11/xdm/xdm-errors

Default error log file if the server is run from xdm(1)

SEE ALSO

Protocols: X Window System Protocol, The X Font Service Protocol, X Display Manager Control Protocol

Server internal documentation: Definition of the Porting Layer for the X v11 Sample Server

AUTHORS

The sample server was originally written by Susan Angebranndt, Raymond Drewry, Philip Karlton, and Todd Newman, from Digital Equipment Corporation, with support from a large cast. It has since been extensively rewritten by Keith Packard and Bob Scheifler, from MIT. Dave Wiggins took over post-R5 and made substantial improvements.

What is the X server?

I have been using Ubuntu for quite some time but, I have no idea what the X server is? I hear it quite often.

I would like to know what the X Server is and what it does. How

/.xinitrc file is used and knowing what the x.org does in the realm of X Server?

d a i s y's user avatar

2 Answers 2

X is an application that manages one or more graphics displays and one or more input devices (keyboard, mouse, etc.) connected to the computer.

It works as a server and can run on the local computer or on another computer on the network. Services can communicate with the X server to display graphical interfaces and receive input from the user.

It’s worth noting, a common component used with an X server is the Window Manager, an application that manages the resizing and moving of windows and decorative elements of windows such as title bars, minimize, and close buttons.

The X server can be started with the ‘startx’ command, or more commonly, from a display manager such as gdm.

/.xinitrc is a shell script used by xinit, that starts the X server when not using a display manager, to define some application to start automatically in the X server.

Что такое x сервер в linux

The X.Org project provides an open source implementation of the X Window System. The development work is being done in conjunction with the freedesktop.org community. The X.Org Foundation is the educational non-profit corporation whose Board serves this effort, and whose Members lead this work.

Xorg (commonly referred to as simply X) is the most popular display server among Linux users. Its ubiquity has led to making it an ever-present requisite for GUI applications, resulting in massive adoption from most distributions. See the Xorg Wikipedia article or visit the Xorg website for more details.

For the alternative and successor, see Wayland.

Installation

Xorg can be installed with the xorg-server package.

Additionally, some packages from the xorg-apps group are necessary for certain configuration tasks. They are pointed out in the relevant sections.

Finally, an xorg group is also available, which includes Xorg server packages, packages from the xorg-apps group and fonts.

Driver installation

The Linux kernel includes open-source video drivers and support for hardware accelerated framebuffers. However, userland support is required for OpenGL and 2D acceleration in X11.

First, identify the graphics card (the Subsystem output shows the specific model):

Then, install an appropriate driver. You can search the package database for a complete list of open-source video drivers:

Xorg searches for installed drivers automatically:

  • If it cannot find the specific driver installed for the hardware (listed below), it first searches for fbdev ( xf86-video-fbdev ), which does not include any 2D or 3D acceleration.
  • If that is not found, it searches for vesa ( xf86-video-vesa ), the generic driver, which handles a large number of chipsets but does not include any 2D or 3D acceleration.
  • If vesa is not found, Xorg will fall back to kernel mode setting, which includes GLAMOR acceleration (see modesetting(4) ).

In order for video acceleration to work, and often to expose all the modes that the GPU can set, a proper video driver is required:

alt=»Tango-view-fullscreen.png» width=»48″ height=»48″ />This article or section needs expansion. alt=»Tango-view-fullscreen.png» width=»48″ height=»48″ />

  1. For Intel graphics on 4th generation and above, see Intel graphics#Installation for available drivers.
  2. Classic OpenGL (non-Gallium3D) drivers for older hardware (Mesa 22.0 and higher have dropped support for i915 classic driver)
  3. For NVIDIA Optimus enabled laptop which uses an integrated video card combined with a dedicated GPU, see NVIDIA Optimus.

Other video drivers can be found in the xorg-drivers group.

Xorg should run smoothly without closed source drivers, which are typically needed only for advanced features such as fast 3D-accelerated rendering for games. The exceptions to this rule are recent GPUs (especially NVIDIA GPUs) not supported by open source drivers.

For a translation of model names (e.g. Radeon RX 6800) to GPU architectures (e.g. RDNA 2), see Wikipedia:List of AMD graphics processing units#Features overview.

  1. Experimental.

Running

The Xorg(1) command is usually not run directly. Instead, the X server is started with either a display manager or xinit.

Configuration

Xorg uses a configuration file called xorg.conf and files ending in the suffix .conf for its initial setup: the complete list of the folders where these files are searched can be found in xorg.conf(5) , together with a detailed explanation of all the available options.

Using .conf files

The /etc/X11/xorg.conf.d/ directory stores host-specific configuration. You are free to add configuration files there, but they must have a .conf suffix: the files are read in ASCII order, and by convention their names start with XX— (two digits and a hyphen, so that for example 10 is read before 20). These files are parsed by the X server upon startup and are treated like part of the traditional xorg.conf configuration file. Note that on conflicting configuration, the file read last will be processed. For this reason, the most generic configuration files should be ordered first by name. The configuration entries in the xorg.conf file are processed at the end.

Using xorg.conf

Xorg can also be configured via /etc/X11/xorg.conf or /etc/xorg.conf . You can also generate a skeleton for xorg.conf with:

This should create a xorg.conf.new file in /root/ that you can copy over to /etc/X11/xorg.conf .

Alternatively, your proprietary video card drivers may come with a tool to automatically configure Xorg: see the article of your video driver, NVIDIA or AMDGPU PRO, for more details.

Input devices

For input devices the X server defaults to the libinput driver ( xf86-input-libinput ), but xf86-input-evdev and related drivers are available as alternative.[1]

Udev, which is provided as a systemd dependency, will detect hardware and both drivers will act as hotplugging input driver for almost all devices, as defined in the default configuration files 10-quirks.conf and 40-libinput.conf in the /usr/share/X11/xorg.conf.d/ directory.

After starting X server, the log file will show which driver hotplugged for the individual devices (note the most recent log file name may vary):

If both do not support a particular device, install the needed driver from the xorg-drivers group. The same applies, if you want to use another driver.

To influence hotplugging, see #Configuration.

For specific instructions, see also the libinput article, the following pages below, or Fedora:Input device configuration for more examples.

Input identification

Mouse acceleration

Extra mouse buttons

Touchpad

Touchscreen

Keyboard settings

Monitor settings

Manual configuration

  • Newer versions of Xorg are auto-configuring, so manual configuration should not be needed.
  • If Xorg is unable to detect any monitor or to avoid auto-configuring, a configuration file can be used. A common case where this is necessary is a headless system, which boots without a monitor and starts Xorg automatically, either from a virtual console at login, or from a display manager.

For a headless configuration, the xf86-video-dummy driver is necessary; install it and create a configuration file, such as the following:

Multiple monitors

See main article Multihead for general information.

More than one graphics card

You must define the correct driver to use and put the bus ID of your graphic cards (in decimal notation).

To get your bus IDs (in hexadecimal):

The bus IDs here are 0:2:0 and 1:0:0 .

Display size and DPI

By default, Xorg always sets DPI to 96 since 2009 (see [2]). A change was made with version 21.1 to provide proper DPI auto-detection, but reverted (see FS#72661).

The DPI of the X server can be set with the -dpi command line option.

Having the correct DPI is helpful where fine detail is required (like font rendering). Previously, manufacturers tried to create a standard for 96 DPI (a 10.3″ diagonal monitor would be 800×600, a 13.2″ monitor 1024×768). These days, screen DPIs vary and may not be equal horizontally and vertically. For example, a 19″ widescreen LCD at 1440×900 may have a DPI of 89×87.

To see if your display size and DPI are correct:

Check that the dimensions match your display size.

If you have specifications on the physical size of the screen, they can be entered in the Xorg configuration file so that the proper DPI is calculated (adjust identifier to your xrandr output):

If you only want to enter the specification of your monitor without creating a full xorg.conf, create a new configuration file. For example ( /etc/X11/xorg.conf.d/90-monitor.conf ):

If you do not have specifications for physical screen width and height (most specifications these days only list by diagonal size), you can use the monitor’s native resolution (or aspect ratio) and diagonal length to calculate the horizontal and vertical physical dimensions. Using the Pythagorean theorem on a 13.3″ diagonal length screen with a 1280×800 native resolution (or 16:10 aspect ratio):

This will give the pixel diagonal length, and with this value you can discover the physical horizontal and vertical lengths (and convert them to millimeters):

Setting DPI manually

For RandR compliant drivers (for example the open source ATI driver), you can set it by:

Proprietary NVIDIA driver

You can manually set the DPI by adding the option under the Device or Screen section:

Manual DPI Setting Caveat

GTK very often overrides the server’s DPI via the optional Xresource Xft.dpi . To find out whether this is happening to you, check with:

With GTK library versions since 3.16, when this variable is not otherwise explicitly set, GTK sets it to 96. To have GTK apps obey the server DPI you may need to explicitly set Xft.dpi to the same value as the server. The Xft.dpi resource is the method by which some desktop environments optionally force DPI to a particular value in personal settings. Among these are KDE and TDE.

Display Power Management

DPMS is a technology that allows power saving behaviour of monitors when the computer is not in use. This will allow you to have your monitors automatically go into standby after a predefined period of time.

Composite

The Composite extension for X causes an entire sub-tree of the window hierarchy to be rendered to an off-screen buffer. Applications can then take the contents of that buffer and do whatever they like. The off-screen buffer can be automatically merged into the parent window, or merged by external programs called compositing managers. For more information, see Wikipedia:Compositing window manager.

Some window managers (e.g. Compiz, Enlightenment, KWin, Marco, Metacity, Muffin, Mutter, Xfwm) do compositing on their own. For other window managers, a standalone composite manager can be used.

List of composite managers

  • Picom — Compositor (a fork of Compton).
  • Xcompmgr — Composite window-effects manager.
  • steamos-compositor-plus — Valve’s compositor, with some added tweaks and fixes.

Tips and tricks

Automation

This section lists utilities for automating keyboard / mouse input and window operations (like moving, resizing or raising).

Tool Package Manual Keysym
input
Window
operations
Note
xautomation xautomation xte(1) Yes No Also contains screen scraping tools. Cannot simulate F13 and more.
xdo xdo xdo(1) No Yes Small X utility to perform elementary actions on windows.
xdotool xdotool xdotool(1) Yes Yes Very buggy and not in active development, e.g: has broken CLI parsing.[3][4]
xvkbd xvkbd AUR xvkbd(1) Yes No Virtual keyboard for Xorg, also has the -text option for sending characters.
AutoKey autokey-qt AUR autokey-gtk AUR documentation Yes Yes Higher-level, powerful macro and scripting utility, with both Qt and Gtk front-ends.

Nested X session

To run a nested session of another desktop environment:

This will launch a Window Maker session in a 1024 by 768 window within your current X session.

This needs the package xorg-server-xnest to be installed.

A more modern way of doing a nested X session is with Xephyr.

Starting an application without a window manager

Starting GUI programs remotely

On-demand disabling and enabling of input sources

With the help of xinput you can temporarily disable or enable input sources. This might be useful, for example, on systems that have more than one mouse, such as the ThinkPads and you would rather use just one to avoid unwanted mouse clicks.

Find the name or ID of the device you want to disable:

For example in a Lenovo ThinkPad T500, the output looks like this:

Disable the device with xinput —disable device , where device is the device ID or name of the device you want to disable. In this example we will disable the Synaptics Touchpad, with the ID 10:

To re-enable the device, just issue the opposite command:

Alternatively using the device name, the command to disable the touchpad would be:

Persistently disable input source

You can disable a particular input source using a configuration snippet:

device is an arbitrary name, and driver_name is the name of the input driver, e.g. libinput . device_name is what is actually used to match the proper device. For alternate methods of targeting the correct device, such as libinput’s MatchIsTouchscreen , consult your input driver’s documentation. Though this example uses libinput, this is a driver-agnostic method which simply prevents the device from being propagated to the driver.

Killing application with hotkey

Run script on hotkey:

Block TTY access

To block tty access when in an X add the following to xorg.conf:

This can be used to help restrict command line access on a system accessible to non-trusted users.

Prevent a user from killing X

To prevent a user from killing X when it is running add the following to xorg.conf:

Killing an application visually

When an application is misbehaving or stuck, instead of using kill or killall from a terminal and having to find the process ID or name, xorg-xkill allows to click on said application to close its connection to the X server. Many existing applications do indeed abort when their connection to the X server is closed, but some can choose to continue.

Rootless Xorg

Xorg may run with standard user privileges instead of root (so-called «rootless» Xorg). This is a significant security improvement over running as root. Note that some popular display managers do not support rootless Xorg (e.g. LightDM or XDM).

You can verify which user Xorg is running as with ps -o user= -C Xorg .

Using xinitrc

To configure rootless Xorg using xinitrc:

  • Run startx as a subprocess of the login shell; run startx directly and do not use exec startx .
  • Ensure that Xorg uses virtual terminal for which permissions were set, i.e. passed by logind in $XDG_VTNR via .xserverrc.
  • If using certain proprietary display drivers, kernel mode settingauto-detection will fail. In such cases, you must set needs_root_rights = no in /etc/X11/Xwrapper.config .
Using GDM

GDM will run Xorg without root privileges by default when kernel mode setting is used.

Session log redirection

When Xorg is run in rootless mode, Xorg logs are saved to

/.local/share/xorg/Xorg.log . However, the stdout and stderr output from the Xorg session is not redirected to this log. To re-enable redirection, start Xorg with the -keeptty flag and redirect the stdout and stderr output to a file:

Alternatively, copy /etc/X11/xinit/xserverrc to

/.xserverrc , and append -keeptty . See [5].

Xorg as Root

As explained above, there are circumstances in which rootless Xorg is defaulted to. If this is the case for your configuration, and you have a need to run Xorg as root, you can configure Xorg.wrap(1) to require root:

Troubleshooting

General

If a problem occurs, view the log stored in either /var/log/ or, for the rootless X default since v1.16, in

/.local/share/xorg/ . GDM users should check the systemd journal. [6]

The logfiles are of the form Xorg.n.log with n being the display number. For a single user machine with default configuration the applicable log is frequently Xorg.0.log , but otherwise it may vary. To make sure to pick the right file it may help to look at the timestamp of the X server session start and from which console it was started. For example:

  • In the logfile then be on the lookout for any lines beginning with (EE) , which represent errors, and also (WW) , which are warnings that could indicate other issues.
  • If there is an empty .xinitrc file in your $HOME , either delete or edit it in order for X to start properly. If you do not do this X will show a blank screen with what appears to be no errors in your Xorg.0.log . Simply deleting it will get it running with a default X environment.
  • If the screen goes black, you may still attempt to switch to a different virtual console (e.g. Ctrl+Alt+F6 ), and blindly log in as root. You can do this by typing root (press Enter after typing it) and entering the root password (again, press Enter after typing it).
  • Check specific pages in Category:Input devices if you have issues with keyboard, mouse, touchpad etc.
  • Search for common problems in AMDGPU, Intel and NVIDIA articles.

Black screen, No protocol specified, Resource temporarily unavailable for all or some users

X creates configuration and temporary files in current user’s home directory. Make sure there is free disk space available on the partition your home directory resides in. Unfortunately, X server does not provide any more obvious information about lack of disk space in this case.

DRI with Matrox cards stopped working

If you use a Matrox card and DRI stopped working after upgrading to Xorg, try adding the line:

to the Device section that references the video card in xorg.conf .

Frame-buffer mode problems

X fails to start with the following log messages:

Program requests «font ‘(null)'»

Error message: unable to load font `(null)’ .

Some programs only work with bitmap fonts. Two major packages with bitmap fonts are available, xorg-fonts-75dpi and xorg-fonts-100dpi . You do not need both; one should be enough. To find out which one would be better in your case, try xdpyinfo from xorg-xdpyinfo , like this:

and use what is closer to the shown value.

Recovery: disabling Xorg before GUI login

If Xorg is set to boot up automatically and for some reason you need to prevent it from starting up before the login/display manager appears (if the system is wrongly configured and Xorg does not recognize your mouse or keyboard input, for instance), you can accomplish this task with two methods.

  • Change default target to rescue.target . See systemd#Change default target to boot into.
  • If you have not only a faulty system that makes Xorg unusable, but you have also set the GRUB menu wait time to zero, or cannot otherwise use GRUB to prevent Xorg from booting, you can use the Arch Linux live CD. Follow the installation guide about how to mount and chroot into the installed Arch Linux. Alternatively try to switch into another tty with Ctrl+Alt + function key (usually from F1 to F7 depending on which is not used by X), login as root and follow steps below.

Depending on setup, you will need to do one or more of these steps:

    the display manager.
  • Disable the automatic start of X.
  • Rename the

X clients started with «su» fail

If you are getting Client is not authorized to connect to server , try adding the line:

to /etc/pam.d/su and /etc/pam.d/su-l . pam_xauth will then properly set environment variables and handle xauth keys.

X failed to start: Keyboard initialization failed

If the filesystem (specifically /tmp ) is full, startx will fail. /var/log/Xorg.0.log will end with:

Make some free space on the relevant filesystem and X will start.

A green screen whenever trying to watch a video

Your color depth is set wrong. It may need to be 24 instead of 16, for example.

SocketCreateListener error

If X terminates with error message SocketCreateListener() failed , you may need to delete socket files in /tmp/.X11-unix . This may happen if you have previously run Xorg as root (e.g. to generate an xorg.conf ).

Invalid MIT-MAGIC-COOKIE-1 key when trying to run a program as root

That error means that only the current user has access to the X server. The solution is to give access to root:

That line can also be used to give access to X to a different user than root.

Xorg-server Fatal server error: (EE) AddScreen/ScreenInit

If the Xorg server is not working randomly and in the Xorg log you see:

Then, this problem may be caused by systemd issue 13943. Set up early KMS start.

Xorg/Руководство

Xorg — это сервер оконной системы X Window server, который позволяет пользователю организовать для себя графическую рабочую среду. Это руководство объясняет что такое Xorg, как его установить и за что отвечают различные параметры конфигурации.

Содержание

Что такое сервер оконной системы X Window?

Графический интерфейс против командной строки

Среднестатистический пользователь может быть встревожен мыслью о том, что ему придётся вводить команды. Почему бы ему не щёлкать мышью с той свободой, какую предоставляет Gentoo (и вообще Linux)? Конечно же, это возможно!

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

Один из самых больших сюрпризов для новых пользователей Linux заключается в том, что графические интерфейсы — это ничего более, чем приложение (или иногда наборы приложений), запущенные на их системе. Это не часть ядра Linux или какой-либо внутренней части системы. Это мощное средство, раскрывающее графические возможности рабочей станции.

Стандарты важны, и стандарт для отрисовки и перемещения окон на экране, взаимодействующий с мышью, клавиатурой, и другим оборудованием, а также включающий иные важные аспекты, был создан и назван X Window System, обычно сокращенный до X11 или просто X. Он используется на Unix, Linux, и Unix-подобных операционных системах по всему миру.

Приложением, которое дает возможность пользователям Linux запускать графический интерфейс и использующее стандарт X11, является Xorg-X11, ответвление проекта XFree86. В XFree86 используется несовместимая с GPL лицензия; следовательно, рекомендуется использовать Xorg. Официальное дерево Portage больше не предоставляет пакеты XFree86.

Проект X.org

Проект X.org создан и поддерживается как свободно распространяемая реализация системы X11 с открытым исходным кодом. А также это основанная на X11 инфраструктура рабочего стола.

Xorg обеспечивает интерфейс между аппаратным обеспечением и графическим программным обеспечением. Помимо этого, Xorg умеет работать в сети, что позволяет запускать программу на одной системе, а смотреть на другой.

Установка

Перед установкой Xorg необходимо подготовить систему. Во-первых, настроим ядро для поддержки устройств ввода и видеокарт. Затем мы подготовим /etc/portage/make.conf так, чтобы были установлены нужные драйверы и пакеты Xorg.

Поддержка устройств ввода

Поддержку устройства событий (event interface) CONFIG_INPUT_EVDEV необходимо включить путем внесения изменений в конфигурацию ядра. Смотрите руководство по конфигурации ядра, если вы не знаете как настроить ваше ядро.

Установка режима в ядре

Современные видеодрайверы с открытым исходным кодом полагаются на поддержку Kernel Mode Setting (KMS). KMS предоставляет улучшенную графическую загрузку с меньшим мерцанием, более быстрым переключением пользователей, встроенной в кадровый буфер консолью, плавным переключением из консоли в Xorg, а также другие возможности.

Отключение устаревших кадровых буферов

Сначала подготовим ядро для KMS. На данном этапе не имеет значения, какой видеодрайвер Xorg будет использоваться.

Далее настройте ядро для использования подходящего драйвера KMS для видеокарты. Intel, NVIDIA и AMD/ATI являются распространенными видеокартами, поэтому смотрите соответствующие настройки ниже для каждой видеокарты.

Intel
NVIDIA

Для видеокарт NVIDIA доступно два варианта. Для систем с полностью открытым исходным кодом рекомендуется использовать открытый драйвер Nouveau. Вторым вариантом является использование пропиетарного драйвера NVIDIA, который официально поддерживается NVIDIA. В статье рекомендуется использовать драйвер Nouveau, однако следует помнить, что для определённых карт драйвер с открытым кодом не обеспечивает полную функциональность.

В дополнение к драйверу в ядре, некоторым картам требуется прошивка с закрытым кодом, встроенная в ядро Linux. В зависимости от выбранного драйвера, следует ознакомиться с соответствующей статьёй, чтобы узнать требуется ли для определённой карты прошивка (из sys-kernel/linux-firmware).

AMD/ATI

Для новых карт AMD/ATI (RadeonHD 2000 и выше) установите пакет sys-kernel/linux-firmware (пакет включает прошивки для драйверов radeon и amdgpu). Когда один из этих пакетов будет установлен, сделайте драйвер Radeon модулем ядра. Или, по желанию, настройте ядро как описано в разделе о прошивке из статьи о Radeon или, для более новых карт от AMD (GCN1.1+), в разделе о прошивке статьи AMDGPU.

Сейчас, когда KMS настроен, продолжите подготовку /etc/portage/make.conf в следующем разделе.

Когда ядро подготовлено, перед установкой Xorg необходимо установить несколько переменных в файле /etc/portage/make.conf .

make.conf

В Portage существует USE-флаг USE=X , включающий поддержку X в других пакетах (он включён по умолчанию в профилях desktop). Убедитесь, что этот USE-флаг добавлен в список включённых USE-флагов:

Первая переменная VIDEO_CARDS . Она используется для установки видеодрайвера, который планируется использовать и который обычно совпадает с используемой видеокартой. Наиболее распространённые значения — nouveau для карт NVIDIA и radeon для ATI. Оба варианта активно разрабатываются и являются хорошо поддерживаемыми драйверами с открытым исходным кодом. Для новых видеокарт AMD (Southern Islands и новее), можно попробовать новый драйвер с открытым исходным кодом amdgpu . Более подробная информация доступна в статье AMDGPU.

intel может быть использован для персональных и планшетных компьютеров с встроенными графическими чипами от Intel. См. Драйверы X для Intel для более детальной информации.

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

make.defaults по умолчанию использует Libinput в качестве драйвера для устройств ввода.

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

В случае необходимости использования других устройств ввода (например сенсорная панель Synaptics), добавьте их в переменную INPUT_DEVICES в файле /etc/portage/make.conf :

Если предложенные настройки не работают, то установите пакета x11-base/xorg-drivers (смотрите следующий пример). Проверьте все доступные варианты и выберите те, которые применимы к системе. Этот пример для системы с клавиатурой, мышью, Synaptics тачпадом и видеокартой Radeon.

USE-флаги имеют следующие значения:

USE flags for x11-base/xorg-server X.Org X servers

debug Enable extra debug codepaths, like asserts and extra output. If you want to get meaningful backtraces see https://wiki.gentoo.org/wiki/Project:Quality_Assurance/Backtraces
elogind Use elogind to get control over framebuffer when running as regular user
minimal Install a very minimal build (disables, for example, plugins, fonts, most drivers, non-critical features)
selinux !!internal use only!! Security Enhanced Linux support, this must be set by the selinux profile or breakage will occur
suid Enable setuid root program(s)
systemd Enable use of systemd-specific libraries and features like socket activation or session tracking
test Enable dependencies and/or preparations necessary to run tests (usually controlled by FEATURES=test but can be toggled independently)
udev Enable virtual/udev integration (device discovery, power and storage device support, etc)
unwind Enable libunwind usage for backtraces
xcsecurity Build Security extension
xephyr Build the Xephyr server
xnest Build the Xnest server
xorg Build the Xorg X server (HIGHLY RECOMMENDED)
xvfb Build the Xvfb server

Emerge

После настройки всех необходимых переменных и USE-флагов можно приступать к установке Xorg:

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

Конфигурация

X server разработан для работы «из коробки», поэтому нет необходимости вручную редактировать файлы настройки. Сервер сам должен определить и настроить устройства — мониторы, клавиатуры и мыши.

Попробуйте использовать startx без предварительного редактирования файлов настройки. Если Xorg не запустится, или будут другие проблемы, тогда необходима ручная настройка Xorg. Она приводится в следующем разделе.

Для запуска Xorg с правами непривилегированного пользователя или включите использование провайдера logind (см. Non root Xorg), или установите USE-флаг suid (см. замечание выше).

Каталог xorg.conf.d

Большинство конфигурационных файлов для Xorg находится в /etc/X11/xorg.conf.d/ . Если этого каталога не существует — создайте его. Каждый файл обладает уникальным именем и оканчивается на .conf . Имена файлов в этом каталоге читаются в буквенно-цифровом порядке. Например, 10-evdev.conf будет прочтен до b-synaptics.conf , и так далее. Файлы в этом каталоге не обязательно должны быть пронумерованы, это сделано для сохранения порядка. Порядок будет полезен при отладке неправильных файлов настройки.

Использование startx

Попробуйте startx для запуска X server. startx — это сценарий (устанавливается из пакета x11-apps/xinit), запускающий сеанс X; иными словами, он запускает X server и некоторые графические приложения вместе с ним. Он решает, какие приложения запустить, основываясь на следующей логике:

  • Если в домашнем каталоге существует файл с названием .xinitrc , будут выполнены команды из него.
  • В противном случае считывается значение переменной XSESSION из файла /etc/env.d/90xsession и выполняется соответствующий сеанс. Значения для XSESSION доступны в /etc/X11/Sessions/ . Для установки сеанса по умолчанию на уровне системы необходимо выполнить:

Если отсутствует оконный менеджер, появится чёрный экран. Так как это также может быть признаком того, что что-то пошло не так, для проверки X можно установить пакеты x11-wm/twm и x11-terms/xterm.

После установки программ снова запустите startx . Должно появиться несколько окон xterm , что является простой проверкой корректной работы сервера X. Удовлетворившись результатами, удалите x11-wm/twm и x11-terms/xterm. Они больше не понадобятся для установки необходимого окружения рабочего стола.

Сеанс также может быть передан в качестве аргумента для startx :

В дополнение к этому, параметры можно передать серверу X, прописав перед ними два дефиса:

Тонкая настройка X

Установка разрешения экрана

Если разрешение экрана установлено неправильно, необходимо проверить два раздела в конфигурации xorg.conf.d . Во-первых, есть раздел Screen со списком разрешений, с которыми может запуститься сервер X. Этот раздел вовсе может не содержать никаких записей о разрешениях. В этом случае Xorg рассчитает характеристики разрешений исходя из информации во втором разделе — Monitor.

Теперь давайте изменим разрешение. В следующем примере из /etc/X11/xorg.conf.d/40-monitor.conf мы добавим строку PreferredMode , так что наш сервер X запустится с разрешением 1440×900 по умолчанию. Пункт Option в разделе Device должен совпадать с именем монитора ( DVI-0 ), которое может быть получено через xrandr . Установите xrandr ( emerge xrandr ) просто для того, чтобы получить эту информацию. Аргумент после имени монитора (в Device ) должен совпадать с Identifier в разделе Monitor .

Запустите X ( startx ) для проверки желаемого разрешения.

Поддержка нескольких мониторов

Больше одного монитора можно установить в /etc/X11/xorg.conf.d/ . Определите для каждого монитора уникальный идентификатор, ориентируясь по его физическому расположению, например «RightOf» или «Above» относительно другого монитора. Следующий пример демонстрирует, как настроить DVI- и VGA-мониторы, когда VGA-монитор расположен по правую руку пользователя.

Настройка клавиатуры

См. статью Keyboard layout switching для определения методов переключения раскладки клавиатуры.

Для установки многоязычной клавиатуры X создайте подходящий файл в /etc/X11/xorg.conf.d/ . Пример для русской раскладки:

Команда «terminate» ( terminate:ctrl_alt_bksp ) дает возможность пользователю убить сеанс X используя комбинацию Ctrl + Alt + Backspace . Однако, это аварийно завершит работу X — следует этого избегать. Это может быть полезно, когда программы полностью «заморозили» экран, или при тонкой настройке окружения Xorg. Будьте осторожны, когда останавливаете рабочий стол этой комбинацией клавиш — большинству программ не нравится, когда их завершают подобным образом. Почти вся информация, не записанная на диск (хранящаяся в «открытых документах»), будет потеряна.

Ввиду того, что драйвер «evdev» может управлять несколькими устройствами (даже не являющимися клавиатурами), может понадобиться ввести ограничение раздела только на некоторые устройства, чтобы остальные работали корректно. Используйте директиву MatchProduct для сопоставления имени устройства, сверившись с man xorg.conf .

За дополнительной информацией о XkbModel и XkbOptions можно обратиться к /usr/share/X11/xkb/rules/base.lst и man xkeyboard-config .

Завершение

Запустите startx и порадуйтесь результату. Поздравляем, вы теперь (надеемся) обладаете рабочим Xorg! Следующим шагом является установка полезного оконного менеджера или окружения рабочего стола, например KDE, GNOME или Xfce. Информация об установке этих рабочих столов может быть найдена здесь на вики.

Смотрите также

    — describes how an unprivileged user can run Xorg without using suid. — a simpler and modern replacement for X display server. — статья Security Handbook о безопасности X сервера. — an open source implementation of the X server. — объясняет что такое Xorg, как его установить и за что отвечают различные параметры конфигурации. — X protocol extension and its CLI tool xrandr are used to manage screen resolutions, rotation and screens with multiply displays in X — the main component of the X Window system which abstracts the hardware and provides the foundation for most graphical user interfaces, like desktop environments or window managers, and their applications.

Внешние ресурсы

Создание и редактирование файлов настройки

man xorg.conf и man evdev содержат краткие, но исчерпывающие сведения о синтаксисе, используемом в их конфигурационных файлах. Удостоверьтесь, что они открыты в терминале, когда редактируете конфигурационные файлы Xorg!

Пример конфигураций можно найти в /usr/share/doc/xorg-server-*/xorg.conf.example.bz2 .

Есть ещё множество онлайн ресурсов о редактировании конфигурационных файлов в /etc/X11/ . Только немногие приведены здесь; используйте ваш любимый поисковик для того, чтобы найти больше.

Другие ресурсы

Больше информации об установке и настройке разных окружений рабочего стола и приложений можно найти в разделе Gentoo desktop resources нашей документации.

При обновлении xorg-server 1.9 или выше прочтите руководство по миграции.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *