Linux command dbus launch

Linux command dbus launch

Библиотека сайта rus-linux.net

На главную -> MyLDP -> Электронные книги по ОС Linux

Beyond Linux From Scratch. Version 2011-12-30
Назад 11. Системные утилиты Вперед

Пакет D-BUS-1.4.16

Знакомимся с пакетом D-BUS

D-BUS является системой шины сообщений, предлагающей приложениям простой способ обмена сообщениями. В составе D-BUS есть как системный демон (для таких событий, как «добавлено новое устройство» или «изменена очередь печати»), так и демон, запускаемый при регистрации в системе каждой новой сессии пользователя (для обычного межпроцессного обмена сообщениями между приложениями пользователя). Кроме того, шина сообщений собирается поверх фреймворка, предназначенного для передачи сообщений вида 1:1 и который может использоваться любыми двумя приложениям для непосредственного взаимодействия друг с другом (минуя демон шины обмена сообщениями).

Известно, что пакет правильно собирается и работает на платформе LFS-7.0.

Информация о пакете

  • Загрузка (HTTP): http://dbus.freedesktop.org/releases/dbus/dbus-1.4.16.tar.gz
  • Контрольная сумма MD5: MD5: 44a2a10678e7e50460879c3eb4453a65
  • Размер загружаемого пакета: 1,8 MB
  • Оценочный размер требуемого дискового пространства: 83 MB
  • Оценочное время сборки: 0,5 SBU

Зависимости пакета D-BUS

Обязательные

Необязательные

Xorg Libraries, D-Bus GLib Bindings-0.98 (для запуска тестов) и Doxygen-1.7.2 (для создания документации по API)

Обратите внимание, что скрипт configure похож на скрипт пакета xmlto-0.0.23, но ничего не делает, т.к. документация XML/HTML уже есть в дереве с исходным кодом.

Конфигурирование ядра

Обеспечьте, чтобы следующий параметр был включен в конфигурации ядра, и перекомпилируйте ядро, если это необходимо:

Установка пакета D-BUS

В роли пользователя root создайте системного пользователя и группу, предназначенные для доступа к шине системных сообщений:

Установите пакет D-BUS с помощью следующих команд (вы, возможно, сначала захотите с помощью команды ./configure —help посмотреть общее описание и добавить к команде configure, представленной ниже, все необходимые параметры):

Инструкции по тестированию приведены ниже.

Теперь в роли пользователя root выполните:

Набор тестов для этого пакета запустить не удастся, если не будет установлен пакет D-Bus GLib Bindings-0.98 . Тесты требуют передачи дополнительных параметров в скрипт configure и обращения к дополнительным функциям двоичных модулей. Такой интерфейс не предназначен для выполнения сборки пакета D-BUS. Если вы хотите запускать тесты для каждого модуля, выполните следующие команды:

Обратите внимание, что если тесты запускаются внутри оболочки Midnight Commander, будет выдано сообщение о том, что они, возможно, не прошли.

Пояснение команд

—libexecdir=/usr/lib/dbus-1.0 : Указывает, что устанавливаться будут только те двоичные файлы, которые используется только пакетом D-BUS, а директорий dbus-1 будет помещен в /usr/lib/dbus-1.0 , а не в /usr/libexec .

—localstatedir=/var : Этот параметр указывает, что файл PID демона, сокет системной шины и файл uuid машины будут созданы в директории /var , а не в директории /usr/var .

—enable-tests : Строит дополнительные пути, используемые при тестировании кода. Конфигурирование заканчивается выдачей замечания, сообщающего об этом.

—enable-asserts : Включает отладочный код, выполняющий проверку инструкций, которые, как предполагается, должны быть истинными. В результате будет предотвращена выдача предупреждения, создаваемого параметром ‘ —enable-tests ‘, которое только указывает, что тесты завершились, и не сообщает о действительных результатах прохождения всех тестов. Однако данный параметр добавит свое собственное сообщение, на которое не следует обращать внимание при сборке пакета.

—disable-static : Предотвращает сборку и установку статических библиотек.

Конфигурирование пакета dbus

Конфигурационные файлы

/etc/dbus-1/session.conf , /etc/dbus-1/system.conf и /etc/dbus-1/system.d/*

Подробнее о конфигурировании

Конфигурационные файлы, указанные выше, по-видимому, менять не нужно. Если изменения необходимы, вы должны создать файл /etc/dbus-1/session-local.conf и/или файл /etc/dbus-1/system-local.conf и внести в них необходимые изменения.

Если в каком-нибудь другом пакете файл .service , используемый D-Bus, устанавливается не в стандартный директорий /usr/share/dbus-1/services , то директорий, куда устанавливается этот файл, нужно добавить в конфигурацию текущей сессии. Например, директорий /usr/local/share/dbus-1/services можно добавить в роли пользователя root с помощью следующих команд:

Загрузочный скрипт

Чтобы в процессе перезагрузки системы автоматически запускать команду dbus-daemon, установите загрузочный скрипт /etc/rc.d/init.d/dbus , имеющийся в пакете blfs-bootscripts-20111226.

Заметим, что это в загрузочном скрипте запускается только общесистемный демон D-BUS. Каждому пользователю, которому требуется доступ к сервисам D-BUS, нужно будет также запустить сессионный демон. Есть много вариантов запуска сессионного демона с помощью команды dbus-launch. Подробности об имеющихся параметрах и возможностях смотрите на странице man команды dbus-launch. Вот некоторые предложения и примеры:

    Добавьте в файл

/.xinitrc строчку с командой dbus-launch в строку файла

/.xinitrc , которая будет запускать графическую среду вашего рабочего стола; смотрите раздел «Конфигурирование базовых пакетов GNOME».
Если вы пользуетесь менеджером xdm или каким-либо другим менеджер дисплеев, в котором происходит обращение к файлу

/.xsession , вы можете добавить в ваш файл

/.xsession строчку с командой dbus-launch, которая будет запускать графическую среду вашего рабочего стола. Синтаксис аналогичен примеру, приведенному в файле

Читайте также:  Для чего нужен помощник по обновлению до windows

/.xinitrc .

  • Если вы пользуетесь менеджером gdm или каким-либо другим менеджер дисплеев, в котором для инициализации сессии применяются настроечные файлы, воспользуйтесь примером, приведенным в разделе «Подробнее о конфигурировании» и описывающим инструкции GDM по созданию файла с командой dbus-launch.
  • В примерах, приведенных ранее, используется команда dbus-launch, указывающая программу, которая должна быть запущена. Преимущество этого подхода в том (когда также используется параметр —exit-with-session ), что в случае, когда указанная программа будет остановлена, сессионный демон будет также остановлен. Для запуска сессионного демона добавьте или в ваши системные или персональные скрипты запуска следующие строки:

    В этом случае сессионый демон не останавливается, когда вы выходите из командной оболочки, так что вы должны в ваш файл

    /.bash_logout добавить следующую строку:

  • Написана рекомендация, в которой предлагаются способы запуска скриптов с помощью сессионного менеджера KDM, имеющемся в рабочем столе KDE. Идеи, изложенные в этой рекомендации, возможно, удастся использовать также и с другими сессионными менеджерами. С рекомендацией можно ознакомиться по ссылке http://www.linuxfromscratch.org/hints/downloads/files/execute-session-scripts-using-kdm.txt t.
  • Описание пакета

    Установленные программы: dbus-cleanup-sockets, dbus-daemon, dbus-daemon-launch-helper, dbus-launch, dbus-monitor, dbus-send, and dbus-uuidgen

    Установленные библиотеки: libdbus-1.

    используется для очистки директория от остатков сокетов

    является демоном шины сообщений D-BUS

    используется для запуска dbus-daemon из скрипта командной оболочки. Как правило, вызывается из скриптов, регистрирующих вход пользователей в систему

    используется для мониторинга сообщений, поступающих через шину сообщений D-BUS

    используется для отправки сообщения в шину сообщений D-BUS

    используется для создания или чтения универсального уникального идентификатора

    содержит функции API, используемые демоном сообщений D-BUS. D-BUS является первой библиотекой, в которой предложены средства обмена сообщениями вида 1:1 между двумя любыми приложениями; dbus-daemon является приложением, использующим эту библиотеку для реализации демона шины сообщений

    Перевод сделан с варианта оригинала, датированного 2011-12-16 19:54:18 +0000

    Источник

    Linux command dbus launch

    dbus-launch [—version] [—sh-syntax] [—csh-syntax] [—auto-syntax] [—exit-with-session] [—autolaunch=MACHINEID] [—config-file=FILENAME] [PROGRAM] [ARGS. ]

    DESCRIPTION

    The dbus-launch command is used to start a session bus instance of dbus-daemon from a shell script. It would normally be called from a user’s login scripts. Unlike the daemon itself, dbus-launch exits, so backticks or the $() construct can be used to read information from dbus-launch .

    With no arguments, dbus-launch will launch a session bus instance and print the address and pid of that instance to standard output.

    You may specify a program to be run; in this case, dbus-launch will launch a session bus instance, set the appropriate environment variables so the specified program can find the bus, and then execute the specified program, with the specified arguments. See below for examples.

    If you launch a program, dbus-launch will not print the information about the new bus to standard output.

    When dbus-launch prints bus information to standard output, by default it is in a simple key-value pairs format. However, you may request several alternate syntaxes using the —sh-syntax, —csh-syntax, —binary-syntax, or —auto-syntax options. Several of these cause dbus-launch to emit shell code to set up the environment.

    With the —auto-syntax option, dbus-launch looks at the value of the SHELL environment variable to determine which shell syntax should be used. If SHELL ends in «csh», then csh-compatible code is emitted; otherwise Bourne shell code is emitted. Instead of passing —auto-syntax, you may explicity specify a particular one by using —sh-syntax for Bourne syntax, or —csh-syntax for csh syntax. In scripts, it’s more robust to avoid —auto-syntax and you hopefully know which shell your script is written in.

    See http://www.freedesktop.org/software/dbus/ for more information about D-Bus. See also the man page for dbus-daemon .

    Here is an example of how to use dbus-launch with an sh-compatible shell to start the per-session bus daemon: You might run something like that in your login scripts.

    Another way to use dbus-launch is to run your main session program, like so: The above would likely be appropriate for

    AUTOMATIC LAUNCHING

    If DBUS_SESSION_BUS_ADDRESS is not set for a process that tries to use D-Bus, by default the process will attempt to invoke dbus-launch with the —autolaunch option to start up a new session bus or find the existing bus address on the X display or in a file in

    Whenever an autolaunch occurs, the application that had to start a new bus will be in its own little world; it can effectively end up starting a whole new session if it tries to use a lot of bus services. This can be suboptimal or even totally broken, depending on the app and what it tries to do.

    There are two common reasons for autolaunch. One is ssh to a remote machine. The ideal fix for that would be forwarding of DBUS_SESSION_BUS_ADDRESS in the same way that DISPLAY is forwarded. In the meantime, you can edit the session.conf config file to have your session bus listen on TCP, and manually set DBUS_SESSION_BUS_ADDRESS, if you like.

    Читайте также:  Bamboo fun cth 661 linux

    The second common reason for autolaunch is an su to another user, and display of X applications running as the second user on the display belonging to the first user. Perhaps the ideal fix in this case would be to allow the second user to connect to the session bus of the first user, just as they can connect to the first user’s display. However, a mechanism for that has not been coded.

    You can always avoid autolaunch by manually setting DBUS_SESSION_BUS_ADDRESS. Autolaunch happens because the default address if none is set is «autolaunch:», so if any other address is set there will be no autolaunch. You can however include autolaunch in an explicit session bus address as a fallback, for example DBUS_SESSION_BUS_ADDRESS=»something:,autolaunch:» — in that case if the first address doesn’t work, processes will autolaunch. (The bus address variable contains a comma-separated list of addresses to try.)

    The —autolaunch option is considered an internal implementation detail of libdbus, and in fact there are plans to change it. There’s no real reason to use it outside of the libdbus implementation anyhow.

    OPTIONS

    —binary-syntax Write to stdout a nul-terminated bus address, then the bus PID as a binary integer of size sizeof(pid_t), then the bus X window ID as a binary integer of size sizeof(long). Integers are in the machine’s byte order, not network byte order or any other canonical byte order.

    —config-file=FILENAME Pass —config-file=FILENAME to the bus daemon, instead of passing it the —session argument. See the man page for dbus-daemon

    —csh-syntax Emit csh compatible code to set up environment variables.

    —exit-with-session If this option is provided, a persistent «babysitter» process will be created that watches stdin for HUP and tries to connect to the X server. If this process gets a HUP on stdin or loses its X connection, it kills the message bus daemon.

    —autolaunch=MACHINEID This option implies that dbus-launch should scan for a previously-started session and reuse the values found there. If no session is found, it will start a new session. The —exit-with-session option is implied if —autolaunch is given. This option is for the exclusive use of libdbus, you do not want to use it manually. It may change in the future.

    —sh-syntax Emit Bourne-shell compatible code to set up environment variables.

    Источник

    dbus-launch

    Utility to start a message bus from a shell script

    SYNOPSIS

    dbus-launch [—version] [—help] [—sh-syntax] [—csh-syntax] [—auto-syntax] [—binary-syntax] [—close-stderr] [—exit-with-session] [—exit-with-x11] [—autolaunch=MACHINEID] [—config-file=FILENAME] [PROGRAM] [ARGS. ]

    DESCRIPTION

    The dbus-launch command is used to start a session bus instance of dbus-daemon from a shell script. It would normally be called from a users login scripts. Unlike the daemon itself, dbus-launch exits, so backticks or the $() construct can be used to read information from dbus-launch.

    With no arguments, dbus-launch will launch a session bus instance and print the address and PID of that instance to standard output.

    You may specify a program to be run; in this case, dbus-launch will launch a session bus instance, set the appropriate environment variables so the specified program can find the bus, and then execute the specified program, with the specified arguments. See below for examples.

    If you launch a program, dbus-launch will not print the information about the new bus to standard output.

    When dbus-launch prints bus information to standard output, by default it is in a simple key-value pairs format. However, you may request several alternate syntaxes using the —sh-syntax, —csh-syntax, —binary-syntax, or —auto-syntax options. Several of these cause dbus-launch to emit shell code to set up the environment.

    With the —auto-syntax option, dbus-launch looks at the value of the SHELL environment variable to determine which shell syntax should be used. If SHELL ends in «csh», then csh-compatible code is emitted; otherwise Bourne shell code is emitted. Instead of passing —auto-syntax, you may explicitly specify a particular one by using —sh-syntax for Bourne syntax, or —csh-syntax for csh syntax. In scripts, its more robust to avoid —auto-syntax and you hopefully know which shell your script is written in.

    See http://www.freedesktop.org/software/dbus/ for more information about D-Bus. See also the man page for dbus-daemon.

    EXAMPLES

    Distributions running dbus-launch as part of a standard X session should run dbus-launch —exit-with-session after the X server has started and become available, as a wrapper around the «main» X client (typically a session manager or window manager), as in these examples:

    dbus-launch —exit-with-session gnome-session

    dbus-launch —exit-with-session openbox

    If your distribution does not do this, you can achieve similar results by running your session or window manager in the same way in a script run by your X session, such as

    Читайте также:  Курсовая работа windows form

    To start a D-Bus session within a text-mode session, do not use dbus-launch. Instead, see dbus-run-session(1).

    Note that in this case, dbus-launch will exit, and dbus-daemon will not be terminated automatically on logout.

    AUTOMATIC LAUNCHING

    If DBUS_SESSION_BUS_ADDRESS is not set for a process that tries to use D-Bus, by default the process will attempt to invoke dbus-launch with the —autolaunch option to start up a new session bus or find the existing bus address on the X display or in a file in

    Whenever an autolaunch occurs, the application that had to start a new bus will be in its own little world; it can effectively end up starting a whole new session if it tries to use a lot of bus services. This can be suboptimal or even totally broken, depending on the app and what it tries to do.

    There are two common reasons for autolaunch. One is ssh to a remote machine. The ideal fix for that would be forwarding of DBUS_SESSION_BUS_ADDRESS in the same way that DISPLAY is forwarded. In the meantime, you can edit the session.conf config file to have your session bus listen on TCP, and manually set DBUS_SESSION_BUS_ADDRESS, if you like.

    The second common reason for autolaunch is an su to another user, and display of X applications running as the second user on the display belonging to the first user. Perhaps the ideal fix in this case would be to allow the second user to connect to the session bus of the first user, just as they can connect to the first users display. However, a mechanism for that has not been coded.

    You can always avoid autolaunch by manually setting DBUS_SESSION_BUS_ADDRESS. Autolaunch happens because the default address if none is set is «autolaunch:», so if any other address is set there will be no autolaunch. You can however include autolaunch in an explicit session bus address as a fallback, for example DBUS_SESSION_BUS_ADDRESS=»something:,autolaunch:» — in that case if the first address doesnt work, processes will autolaunch. (The bus address variable contains a comma-separated list of addresses to try.)

    The —autolaunch option is considered an internal implementation detail of libdbus, and in fact there are plans to change it. Theres no real reason to use it outside of the libdbus implementation anyhow.

    OPTIONS

    The following options are supported:

    Choose —csh-syntax or —sh-syntax based on the SHELL environment variable.

    Write to stdout a nul-terminated bus address, then the bus PID as a binary integer of size sizeof(pid_t), then the bus X window ID as a binary integer of size sizeof(long). Integers are in the machines byte order, not network byte order or any other canonical byte order.

    Close the standard error output stream before starting the D-Bus daemon. This is useful if you want to capture dbus-launch error messages but you dont want dbus-daemon to keep the stream open to your application.

    Pass —config-file=FILENAME to the bus daemon, instead of passing it the —session argument. See the man page for dbus-daemon

    Emit csh compatible code to set up environment variables.

    If this option is provided, a persistent «babysitter» process will be created, and will connect to the X server. If it cannot do so, launching fails. If the «babysitter» process loses its X connection, it kills the message bus daemon, disconnecting all of its clients (which should exit in response). This avoids having leftover daemon processes from a user X session, after the X session has ended.

    If this option is provided, a persistent «babysitter» process will be created, as if for —exit-with-x11. If it cannot connect to the X server, it will monitor the terminal from which dbus-launch was started instead, and if it gets a HUP on stdin, the message bus daemon will be killed. This option is not recommended, since it will consume input from the terminal where it was started; it is mainly provided for backwards compatibility.

    This option implies that dbus-launch should scan for a previously-started session and reuse the values found there. If no session is found, it will start a new session. The —exit-with-session option is implied if —autolaunch is given. This option is for the exclusive use of libdbus, you do not want to use it manually. It may change in the future.

    Emit Bourne-shell compatible code to set up environment variables.

    Print the version of dbus-launch

    Print the help info of dbus-launch

    NOTES

    If you run dbus-launch myapp (with any other options), dbus-daemon will not exit when myapp terminates: this is because myapp is assumed to be part of a larger session, rather than a session in its own right.

    Источник

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