bus -- A simple daemonless system for broadcasting messages locally
*******************************************************************

Copyright © 2015 Mattias Andrée

     Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled ``GNU Free Documentation License''.

Overview
********

bus is a stupid-simple, thrilless, daemonless interprocess communication system for broadcasting messages. It is a lightweight alternative to a two-phase interprocess flexible barrier.

bus uses a System V semaphore array and System V shared memory. Buses are named; the key of the semaphore array and the shared memory is stored in a regular file.

The shared memory used by bus is always 2048 bytes. Additionally all messages should be encoded in UTF-8 and not contain any NULL characters, except they must always end with a NULL byte. Furthermore messages should be prefixed with the process identifer of the process whence the message originated, followed by a space. If the process is ephemeral (The process exits after the broadcast, or shortly thereafter.), 0 should be used instead of the process identifier.

Communication over bus is synchronous. The broadcast call does not return until all listeners have received (and copied) the message. A malfunctioning program can lock the bus.

This software package contains a C library and a command line utility. The package python-bus provides a Python 3 module.

Standard
********

The command bus create can be used to create new buses. By convention, buses should be stored in $XDG_RUNTIME_DIR/bus, this is what bus create does if no pathname is given. The pathname of the bus should be tracked using BUS_X, where X is replaced with either:

GENERIC
     For the bus used in generic cases. That is all but the cases of the buses listed below.

AUDIO
     For the bus used in with the audio subsystem is involved.

VIDEO
     For the bus used in with the video subsystem is involved.

INPUT
     For the bus used in with the input subsystem is involved.

FILES
     For the bus used in with the storage subsystem is involved.

This list may be extended in the future. Therefore, and for other conventions, project-private buses should be tracked using X_BUS, where X is the project name.

Messages broadcasted on a bus cannot be longer than 2047 bytes, excluding NUL termination. Message should be encoded in UTF-8, and most not contain the NUL character.

Broadcasted message should start with the process ID whence the message originated, followed by a single regular space. If the process is ephemeral (The process exits after the broadcast, or shortly thereafter.), 0 should be used instead of the process identifier.

Invoking
********

bus includes the following commands:

create
     Create a bus. See bus create for more information.

remove
     Remove a bus. See bus remove for more information.

listen
     Listen for new message on a bus. See bus listen for more information.

wait
     Listen for one new message only on a bus. See bus wait for more information.

broadcast
     Broadcast a message on a bus. See bus broadcast for more information.

chmod
     Change permissions on a bus. See bus chmod for more information.

chown
     Change ownership of a bus. See bus chown for more information.

chgrp
     Change group ownership of a bus. See bus chgrp for more information.

Upon successful completion, these commands exit with the value 0. On failure, they exit with the value 1. If the command is not recognised the exit value is 2.

bus create
==========

The syntax for invocation of bus create is

     bus create [-x] [--] [PATHNAME]

The command creates a bus and stores the key to it in the file PATHNAME. If PATHNAME is omitted, a random pathname in $XDG_RUNTIME_DIR/bus will be used and printed to stdout.

If -x is used, the command will fail if the file PATHNAME already exists.

bus remove
==========

The syntax for invocation of bus remove is

     bus remove [--] PATHNAME

The command removes the bus whose key is stored in the file PATHNAME.  The file holding the key is also unlinked.

bus listen
==========

The syntax for invocation of bus command is

     bus listen [--] PATHNAME COMMAND

The command listens for new messages on the bus whose key is stored in the file PATHNAME. Once a message is received, COMMAND will be spawned with the environment variable msg (lowercased) set to the received message. POSIX shell syntax applies to COMMAND.

bus wait
========

The syntax for invocation of bus wait is

     bus wait [--] PATHNAME COMMAND

The command listens for a new message on the bus whose key is stored in the file PATHNAME. Once a message is received, the process will stop listening for more messages and COMMAND will be spawned with the environment variable msg (lowercased) set to the received message. POSIX shell syntax applies to COMMAND.

bus broadcast
=============

The syntax for invocation of bus broadcast is

     bus broadcast [-n] [--] PATHNAME MESSAGE

The command broadcasts the message MESSAGE on the bus whose key is stored in the file PATHNAME.

bus chmod
=========

The syntax for invocation of bus chmod is

     bus chmod [--] PERMISSIONS PATHNAME

This command changes who have access to the bus whose key is stored in the file PATHNAME. In the permissions, the owner, the group, and others (not in tgroup) are represented by the symbols u (u stands for `user'.), g, and o, respectively. The permissions string is imagined to have always be prefixed with an =. This symbols means that all user classes list after it, and only those classes, as permission to use the bus. Similarly the symbols + and - can be used to grant and revoke access, respectively. The symbols =, +, and - can be mixed, and are interpreted from left to right. Alternatively the permissions string can be a octal number, where the  owner is represented by any bit in 700 (100, 200, or 400, or any combination thereof), the group is represented by any bit in 70, and others (not in the group) is represented by any bit in 7.

The current permission of the bus can be retrieved by running stat over the file PATHNAME.

bus chown
=========

The syntax for invocation of bus chown is

     bus chown [--] OWNER[:GROUP] PATHNAME

This command changes the owner, that owns the bus whose key is stored in the file PATHNAME, to the specified owner. The owner can be specified either with a numerical user identifier or with a user name. If a group is specified, the bus's owner-group will be set to that group, otherwise the group will remain unchanged (not changed to the group of the new owner.) The group can be specified either with a numerical group identifier or with a group name.

The current ownership of the bus can be retrieved by running stat over the file PATHNAME.

bus chgrp
=========

The syntax for invocation of bus chgrp is

     bus chgrp [--] GROUP PATHNAME

This command changes the group, that owns the bus whose key is stored in the file PATHNAME, to the specified group. The group can be specified either with a numerical group identifier or with a group name.

The current ownership of the bus can be retrieved by running stat over the file PATHNAME.

Interface
*********

To use libbus in your C program, include the header file <bus.h> and link with the flag -lbus.

With exception to bus_poll and bus_poll_timed, all functions return 0 upon successful completion, and -1 in case of failure. bus_poll and bus_poll_timed return NULL on failure. On failure on all functions set errno to indicate what went wrong.

<bus.h> defines the following functions:

int bus_create(const char *file, int flags, char **out_file)
     This function creates a bus with the asscoiated pathname specifed by the value of the parameter file. If file is NULL a random pathname is selected. This pathname adheres to the convention set forth by in Standard.

     If file is not NULL the function fails if the file already exists if flags contains BUS_EXCL. Otherwise if file is not NULL, the function does nothing if the file already exists.

     If flags contains BUS_INTR, the function fails if it is interrupted.

     Unless out_file is NULL, the pathname of the bus should be stored in a new char array stored in *out_file. The caller must free the allocated stored in *out_file.

     If the processes cannot allocate enough memory to perform the action, the function sets errno to ENOMEM and fails. It may also fail and set errno to any of the errors specified for the system calls open and write.

int bus_unlink(const char *file)
     This function removes the bus assoicated with the pathname stored in the parameter file. The function also unlinks the file.

     The function may set errno to any of the following values and fail for the specified reasons:

     EINVAL
          The bus does not exist.

     EACCES
          Operation permission is denied to the calling process.

     EPERM
          The user does not have permission to remove the bus.

     It may also fail and set errno to any of the errors specified for the system calls unlink and open, and the functions semget and shmget.

int bus_open(bus_t *bus, const char *file, int flags)
     This function acquires resources required for the process to use the bus associated with the filename stored in the parameter file. The function also stores the resources in bus for use by other bus functions.

     Values for flags are constructed by a bitwise inclusive OR of flags from the following list.

     BUS_RDONLY
          The process will only be using the bus for receiving messages.

     BUS_WRONLY
          The process will only be using the bus for sending messages.

     BUS_RDWR
          The process will use the bus for both receiving and sending messages.

     The function may set errno to any of the following values and fail for the specified reasons:

     ENOMEM
          The process cannot allocate enough memory to perform the action.

     EACCES
          Operation permission is denied to the calling process.

     EINVAL
          The described bus does not exist.

     It may also fail and set errno to any of the errors specified for the system call open.

int bus_close(bus_t *bus)
     This function disposes of resources allocated to the process, as referenced in the parameter bus.

     The function fails and sets errno to EINVAL if the bus does not exist.

int bus_write(const bus_t *bus, const char *message, int flags)
     This function broadcasts a message on the bus whose information is stored in the parameter bus. The message read by the function is stored in the parameter message. It may not exceeed 2048 bytes, including NUL termination.

     The function shall fail, and set errno to EAGAIN, if the call would suspend the process and flags contains BUS_NOWAIT.

     The function may fail and set errno to any of the errors specified for the function semop.

int bus_write_timed(const bus_t *bus, const char *message, const struct timespec *timeout, clockid_t clockid)
     This function behaves like bus_write, except if it is not able to write the message within the specified time, it will fail and set errno to EAGAIN. The time is specified as an absolute time using the parameter timeout. The behaviour is unspecified if timeout is NULL. timeout is measured with the clock whose identifier is specified by the parameter clockid. This clock must be a predicitable clock (There are probably other, undocumented, seemingly arbitrary restrictions too.).

     The function may fail and set errno to any of the errors specified for the functions semop and clock_gettime.

int bus_read(const bus_t *bus, int (*callback)(const char *message, void *user_data), void *user_data)
     This function waits for new message to be sent on the bus specified in the bus parameter, as provieded by a previous call to the function bus_open. Once a message is received, the parameter-function callback is invoked. The parameter message in callback is the received message, and user_data in callback should be user_data from bus_read. However, once the function [bus_read] has ensured that it will receive any message sent on the bus, it shall invoke the parameter-function callback with message set to NULL, to notify the process that it can perform any action that requires that it is listening on the bus.

     After callback returns, message may be override. Therefore callback should copy message and start a new thread that uses the copy of message. callback shall return -1 on failure, 0 if the function [bus_read] should stop listening, or 1 if the function should continue listening.

     The function may fail and set errno to any of the errors specified for the function semop.

int bus_read_timed(const bus_t *bus, int (*callback)(const char *message, void *user_data), void *user_data, const struct timespec *timeout, clockid_t clockid)
     This function behaves like bus_read, except it will automatically fail and set errno to EAGAIN when the specified time has passed. The time is specified as an absolute time using the parameter timeout. The behaviour is unspecified if timeout is NULL. timeout is measured with the clock whose identifier is specified by the parameter clockid. This clock must be a predicitable clock (There are probably other, undocumented, seemingly arbitrary restrictions too.).

     The function may fail and set errno to any of the errors specified for the functions semop and clock_gettime.

int bus_poll_start(bus_t *bus)
int bus_poll_stop(const bus_t *bus)
const char *bus_poll(bus_t *bus, int flags)
const char *bus_poll_timed(bus_t *bus, const struct timespec *timeout, clockid_t clockid)
     The function bus_poll waits for a message to be broadcasted on the bus, and return the message it receives. The function fails if flags contains BUS_NOWAIT and there is not already a message waiting on the bus. Received messages shall be copied and parsed, and acted upon, in a separate thread, and the function bus_poll or the function bus_poll_stop called again as soon as possible.

     The funcion bus_poll_start must be called before bus_poll is called for the first time. When the process is done listening on the bus, it must call the function bus_poll_stop.

     The function bus_poll_timed behaves like the function bus_poll, except if it is not able to read a message within the specified time, it will fail and set errno to EAGAIN. The time is specified as an absolute time using the parameter timeout. The behaviour is unspecified if timeout is NULL. timeout is measured with the clock whose identifier is specified by the parameter clockid. This clock must be a predicitable clock (There are probably other, undocumented, seemingly arbitrary restrictions too.).

     Upon successful completion, the functions bus_poll and bus_poll_timed returns the received message.

     These functions may fail and set errno to any of the errors specified for the function semop. The function bus_poll_timed may also set errno to any of the errors specified for clock_gettime.

int bus_chown(const char *file, uid_t owner, gid_t group)
     This function changes the owner and the group of the bus, associated with the file whose pathname is stored in the parameter file, to the owner and group specified by the parameters owner and group, respectively.

     The current ownership of a bus can be retrieved by calling stat over the pathname of the bus.

     The function may fail and set errno to any of the errors specified for the functions bus_open, chown, semget, shmget, and shmctl as well as any errors specified for the commands IPC_STAT and IPC_SET for the function semctl.

int bus_chmod(const char *file, mode_t mode)
     This function gives access to the bus associated with the file whose pathname is stored in the parameter file according to the following rules:

       * If mode contains any of the bits S_IRWXU contains, the owner should be given full access to the bus. Otherwise the owner should have no access.

       * If mode contains any of the bits S_IRWXG contains, the group should be given read and write access to the bus. Otherwise the group should have no access.

       * If mode contains any of the bits S_IRWXO contains, users that are neither the owner nor member of the group should be given read and write access to the bus. Otherwise they should have no access.

     The current permissions of a bus can be retrieved by calling stat over the pathname of the bus.

     The function may fail and set errno to any of the errors specified for the functions bus_open, chmode, semget, shmget, and shmctl as well as any errors specified for the commands IPC_STAT and IPC_SET for the function semctl.

There is not reason for poking around in bus_t (struct bus). It should be considered opaque. You can read the documentation in <bus.h> if you want to know what is in it.

Protocol
********

bus is built upon following three procedures.

create

     Select a filename.

     Create XSI semaphore array {S = 0, W = 0, X = 1, Q = 0, N = 0}
     with random key. Store the semaphore array's key in decimal form
     on the first line in the selected file.

     Create XSI shared memory, with an allocation of 2048 bytes, with
     a random key. Store the shared memory's key in decimal form on
     the second line in the selected file.

broadcast

     with P(X):
       Z(W)
       Write NUL-terminate message to shared memory
       with V(N): -- (1)
         Q := 0
         Z(S)

     -- (1) may be omitted if semaphores are known that
        P(), Z(), V() cannot create a race condition
        with a processes running Z().

listen

     with V(S):
       forever:
         V(Q)
         Z(Q)
         Read NUL-terminated message from shared memory
         if breaking:
           break
         with V(W):
           with P(S):
             Z(S)
             Z(N)

V(a) means that semaphore a is released.

P(a) means that semaphore a is acquired.

Z(a) means that the process waits for semaphore a to become 0.

with P(a) that P(a) is done before the entering the scope, and V(a) is done when exiting the scope. It also means that these actions [P(a) and V(a)] are undone when the process exits, or if the call fails.

with V(a) is to V(a) as with P(a) is to P(a).

Rationale
*********

We need an interprocess communication system similar to message queues. But we need broadcasting rather than anycasting, so we have a fast, simple and daemonless system for announcing events to any processes that might be interested.

Examples
********

This chapter contains usecase examples and API-demonstrations. You will find that they are (on a standard installation) installed on your system.

Audio-volume control
====================

Assume you have program that display the audio volume. This program checks every second third if the volume have changed.

Also assume that you use amixer to change the volume, most often by using keybindings via xbindkeys.

To reduce the delay, you want to send a signal to the monitor program that the volume have changed. For this more primitive IPC is sufficient, but lets assume there are other programs interested in this information too.

To accomplish this, you create a wrapper for amixer that broadcasts updates on a bus. This wrapper is installed as ~/.local/bin/amixer, and ~/.local/bin/ is included in $PATH before /usr/bin.

Before starting run ./init, this code is should be run from your profile file if you want to implement this on your system. After running ./init, you can start one or more listeners by running ./alsa-monitor.

To change the volume run ./amixer -c 0 -- set Master 5%+ or similar.

When you are done run ./cleanup.

./amixer
........

     #!/bin/sh
     /usr/bin/amixer "$@"
     for arg in "$@"; do
       if [ "${arg}" = "set" ]  || \
          [ "${arg}" = "sset" ] || \
          [ "${arg}" = "cset" ]; then
         exec bus broadcast "/tmp/example-bus" '0 volume-changed *'
       fi
     done

./cleanup
.........

     #!/bin/sh
     exec bus remove "/tmp/example-bus"

./init
......

     #!/bin/sh
     bus create "/tmp/example-bus"

     # The following code is more suitable in the real world,
     # if used, the other files should use "${BUS_AUDIO}"
     # instead of "/tmp/example-bus".
     #
     # export BUS_AUDIO="${XDG_RUNTIME_DIR}/bus/audio"
     # if [ ! -f "${BUS_AUDIO}" ]; then
     #   bus create "${BUS_AUDIO}"
     # fi

./monitor
.........

     #!/bin/sh
     if [ $# = 1 ]; then
       if [ "$(echo "${1}" | cut -d ' ' -f 2)" = "volume-changed" ]; then
         printf '\e[H\e[2J'
         amixer get Master
       fi
       exit 0
     fi

     exec 2>/dev/null

     printf '\e[?1049h\e[H\e[2J'
     trap -- "printf '\e[?1049l'" SIGINT
     bus listen "/tmp/example-bus" \'"${0/\'/\'\\\'\'}"\'' "${msg}"'

Telephony and music
===================

Assume you have a music player and a telephony program. You might like it if the music player pauses whenever you make or receive a call. You may also like it, if the music resumed when the call ended.

In this example we will assume you the have mocp (moc package) running. And we will use the shell to simulate a telephony program.

First of, run make to build this example. Before starting run ./init. And when you are done run ./cleanup.

In one terminal run ./monitor. This program will pause mocp when you make or receive a call, it will also resume mocp when all calls have ended if it did pause mocp.

Then start any positive number of terminals. We will pretend that each of them are telephony programs. To make or receive a call, run ./receive-or-make-call, when you want to end the pretend call, run ./end-call from the terminal (or more accurately, from the same process.)

./Makefile
..........

     COMMANDS = init cleanup monitor end-call receive-or-make-call

     all: ${COMMANDS}
     %: %.c
             ${CC} -Wall -Wextra -pedantic -std=c99 -lbus -o $@ $<
     clean:
             -rm ${COMMANDS}

     .PHONY: all clean

./cleanup.c
...........

     #include <bus.h>
     #include <stdio.h>

     int main()
     {
       return bus_unlink("/tmp/example-bus") && (perror("cleanup"), 1);
     }

./end-call.c
............

     #include <bus.h>
     #include <stdio.h>
     #include <unistd.h>
     #include <stdint.h>

     #define t(stmt)  if (stmt) goto fail

     static char message[BUS_MEMORY_SIZE];

     int main()
     {
       bus_t bus;
       sprintf(message, "%ji unforce-pause", (intmax_t)getppid());
       /* Yes, PPID; in this example we pretend the shell is the telephony process. */
       t (bus_open(&bus, "/tmp/example-bus", BUS_WRONLY));
       t (bus_write(&bus, message, 0));
       bus_close(&bus);
       return 0;

     fail:
       perror("end-call");
       bus_close(&bus);
       return 1;
     }

./init.c
........

     #include <bus.h>
     #include <stdio.h>

     int main()
     {
       return bus_create("/tmp/example-bus", 0, NULL) && (perror("init"), 1);
     }

./monitor.c
...........

     #include <bus.h>
     #include <stdio.h>
     #include <stdlib.h>
     #include <string.h>

     #define t(stmt)  if (stmt) goto fail

     static size_t pauser_count = 0;
     static size_t pausers_size = 0;
     static char* pausers = NULL;

     static int is_moc_playing(void)
     {
       return !WEXITSTATUS(system("env LANG=C mocp -i 2>/dev/null |"
                                  "grep 'State: PLAY' >/dev/null"));
     }

     /* In a proper implementation, message whould be copyied, and then
      * a new thread would be created that parsed the copy. But that is
      * too much for an example, especially since it would also require
      * a mutex to make sure two threads do not modify data at the same
      * time, causing chaos. */
     static int callback(const char *message, void *user_data)
     {
       char *msg = NULL;
       size_t len = 0;
       if (message == 0)
         return 1;
       while ((len < 2047) && message[len])
         len++;
       msg = malloc((len + 1) * sizeof(char));
       t (msg == NULL);
       memcpy(msg, message, len * sizeof(char));
       msg[len] = 0;
       /* BEGIN run as in a separate thread */
       if (pauser_count || is_moc_playing()) {
         char *begin = strchr(msg, ' ');
         ssize_t pid;
         int requests_pause;
         if (begin == NULL)
           goto done;
         *begin++ = 0;
         pid = (ssize_t)atoll(msg);
         if (pid < 1) /* We need a real PID, too bad there is
                       * no convient way to detect if it dies. */
           goto done;
         if ((strstr(begin, "force-pause ") == begin) ||
             !strcmp(begin, "force-pause"))
           requests_pause = 1;
         else if ((strstr(begin, "unforce-pause ") == begin) ||
                  !strcmp(begin, "unforce-pause"))
           requests_pause = 0;
         else
           goto done;
         if ((size_t)pid >= pausers_size) {
           pausers = realloc(pausers, (size_t)(pid + 1) * sizeof(char));
           t (pausers == NULL); /* Let's ignore the memory leak. */
           memset(pausers + pausers_size, 0,
                  ((size_t)(pid + 1) - pausers_size) * sizeof(char));
           pausers_size = (size_t)(pid + 1);
         }
         if (pausers[pid] ^ requests_pause) {
           pauser_count += requests_pause ? 1 : -1;
           pausers[pid] = requests_pause;
           if (pauser_count == (size_t)requests_pause)
             system(requests_pause ? "mocp -P" : "mocp -U");
         }
       }
       /* END run as in a separate thread */
       goto done;
       (void) user_data;

     fail:
       perror("monitor");
       return -1;

     done:
       free(msg);
       return 1;
     }

     int main()
     {
       bus_t bus;
       t (bus_open(&bus, "/tmp/example-bus", BUS_RDONLY));
       t (bus_read(&bus, callback, NULL));
       bus_close(&bus);
       free(pausers);
       return 0;

     fail:
       perror("monitor");
       bus_close(&bus);
       free(pausers);
       return 1;
     }

./receive-or-make-call.c
........................

     #include <bus.h>
     #include <stdio.h>
     #include <unistd.h>
     #include <stdint.h>

     #define t(stmt)  if (stmt) goto fail

     static char message[BUS_MEMORY_SIZE];

     int main()
     {
       bus_t bus;
       sprintf(message, "%ji force-pause", (intmax_t)getppid());
       /* Yes, PPID; in this example we pretend the shell is the telephony process. */
       t (bus_open(&bus, "/tmp/example-bus", BUS_WRONLY));
       t (bus_write(&bus, message, 0));
       bus_close(&bus);
       return 0;

     fail:
       perror("receive-or-make-call");
       bus_close(&bus);
       return 1;
     }

Timed
=====

This example shows how to use timed operations.

First of, run make to build this example.

To start the example run ./init. When you are done run ./cleanup.

Running instances of ./poll will wait for new messages continuously, but with one second timeouts.

./slow-poll works like ./poll, except it will sleep for one second every time it receives a message.

Running instances of ./read will read for ten seconds and then time out.

./poll, ./read, and ./slow-poll will stop if the message "stop" is broadcasted.

./write will wait for atmost a tenth of a seconds before failing. This means that if two instances of ./write is started at the same time one of them will fail if ./slow-poll is running.

./poll, ./read, ./init and ./cleanup are run without any additional arguments. ./write is run with the message as the second argument.

./Makefile
..........

     COMMANDS = init cleanup write poll read slow-poll

     all: ${COMMANDS}
     %: %.c
             ${CC} -Wall -Wextra -pedantic -std=c99 -lbus -o $@ $<
     clean:
             -rm ${COMMANDS}

     .PHONY: all clean

./cleanup.c
...........

     #include <bus.h>
     #include <stdio.h>

     int main()
     {
       return bus_unlink("/tmp/example-bus") && (perror("cleanup"), 1);
     }

./init.c
........

     #include <bus.h>
     #include <stdio.h>

     int main()
     {
       return bus_create("/tmp/example-bus", 0, NULL) && (perror("init"), 1);
     }

./poll.c
........

     #include <bus.h>
     #include <stdio.h>
     #include <unistd.h>
     #include <string.h>
     #include <errno.h>

     #define t(stmt)  if (stmt) goto fail

     int main()
     {
       bus_t bus;
       const char *message;
       long long tick = 0;
       struct timespec timeout;
       t (bus_open(&bus, "/tmp/example-bus", BUS_RDONLY));
       t (bus_poll_start(&bus));
       for (;;) {
         t(clock_gettime(CLOCK_MONOTONIC, &timeout));
         timeout.tv_sec += 1;
         message = bus_poll_timed(&bus, &timeout, CLOCK_MONOTONIC);
         if (message == NULL) {
           t (errno != EAGAIN);
           printf("waiting... %lli\n", ++tick);
           continue;
         }
         tick = 0;
         message = strchr(message, ' ') + 1;
         if (!strcmp(message, "stop"))
           break;
         printf("\033[01m%s\033[21m\n", message);
       }
       t (bus_poll_stop(&bus));
       bus_close(&bus);
       return 0;

     fail:
       perror("poll");
       bus_poll_stop(&bus);
       bus_close(&bus);
       return 1;
     }

./read.c
........

     #include <bus.h>
     #include <stdio.h>
     #include <unistd.h>
     #include <string.h>
     #include <errno.h>

     #define t(stmt)  if (stmt) goto fail

     static int callback(const char *message, void *user_data)
     {
       (void) user_data;

       if (message == NULL)
         return 1;

       message = strchr(message, ' ') + 1;
       if (!strcmp(message, "stop"))
         return 0;
       printf("%s\n", message);
       return 1;
     }

     int main()
     {
       bus_t bus;
       struct timespec timeout;
       t (bus_open(&bus, "/tmp/example-bus", BUS_RDONLY));
       t (clock_gettime(CLOCK_MONOTONIC, &timeout));
       timeout.tv_sec += 10;
       t (bus_read_timed(&bus, callback, NULL, &timeout, CLOCK_MONOTONIC));
       bus_close(&bus);
       return 0;

     fail:
       perror("poll");
       bus_poll_stop(&bus);
       bus_close(&bus);
       return 1;
     }

./slow-poll.c
.............

     #include <bus.h>
     #include <stdio.h>
     #include <unistd.h>
     #include <string.h>
     #include <errno.h>

     #define t(stmt)  if (stmt) goto fail

     int main()
     {
       bus_t bus;
       const char *message;
       long long tick = 0;
       struct timespec timeout;
       t (bus_open(&bus, "/tmp/example-bus", BUS_RDONLY));
       t (bus_poll_start(&bus));
       for (;;) {
         t (clock_gettime(CLOCK_MONOTONIC, &timeout));
         timeout.tv_sec += 1;
         message = bus_poll_timed(&bus, &timeout, CLOCK_MONOTONIC);
         if (message == NULL) {
           t (errno != EAGAIN);
           printf("waiting... %lli\n", ++tick);
           continue;
         }
         tick = 0;
         message = strchr(message, ' ') + 1;
         if (!strcmp(message, "stop"))
           break;
         printf("\033[01m%s\033[21m\n", message);
         sleep(1);
       }
       t (bus_poll_stop(&bus));
       bus_close(&bus);
       return 0;

     fail:
       perror("poll");
       bus_poll_stop(&bus);
       bus_close(&bus);
       return 1;
     }

./write.c
.........

     #include <bus.h>
     #include <stdio.h>
     #include <unistd.h>
     #include <stdint.h>

     #define t(stmt)  if (stmt) goto fail

     static char message[BUS_MEMORY_SIZE];

     int main(int argc, char *argv[])
     {
       bus_t bus;
       struct timespec timeout;
       if (argc < 2) {
         fprintf(stderr, "%s: USAGE: %s message\n", argv[0], argv[0]);
         return 2;
       }
       sprintf(message, "0 %s", argv[1]);
       t (bus_open(&bus, "/tmp/example-bus", BUS_WRONLY));
       t (clock_gettime(CLOCK_MONOTONIC, &timeout));
       timeout.tv_nsec += 100000000L;
       t (bus_write_timed(&bus, message, &timeout, CLOCK_MONOTONIC));
       bus_close(&bus);
       return 0;

     fail:
       perror("write");
       bus_close(&bus);
       return 1;
     }

Nonblocking
===========

This example shows how to use bus_poll instead of bus_read, and how to do non-blocking polling and non-blocking writing.

First of, run make to build this example.

To start the example run ./init. When you are done run ./cleanup.

Running instances of ./poll will check every second if there is a new inbound message. Between these checks ./write will wait for all ./poll:s to receive the message. This means that ./write blocks while ./poll sleeps. If two or more instances of ./write is started at approximately the same time, only one will continue to write a message on the bus, the others will fail.

./poll will stop if the message ``stop'' is broadcasted.

./poll, ./init and ./cleanup are run without any additional arguments. ./write is run with the message as the second argument.

./Makefile
..........

     COMMANDS = init cleanup write poll

     all: ${COMMANDS}
     %: %.c
             ${CC} -Wall -Wextra -pedantic -std=c99 -lbus -o $@ $<
     clean:
             -rm ${COMMANDS}

     .PHONY: all clean

./cleanup.c
...........

     #include <bus.h>
     #include <stdio.h>

     int main()
     {
       return bus_unlink("/tmp/example-bus") && (perror("cleanup"), 1);
     }

./init.c
........

     #include <bus.h>
     #include <stdio.h>

     int main()
     {
       return bus_create("/tmp/example-bus", 0, NULL) && (perror("init"), 1);
     }

./poll.c
........

     #include <bus.h>
     #include <stdio.h>
     #include <unistd.h>
     #include <string.h>
     #include <errno.h>

     #define t(stmt)  if (stmt) goto fail

     int main()
     {
       bus_t bus;
       const char *message;
       long long tick = 0;
       t (bus_open(&bus, "/tmp/example-bus", BUS_RDONLY));
       t (bus_poll_start(&bus));
       for (;;) {
         message = bus_poll(&bus, BUS_NOWAIT);
         if (message == NULL) {
           t (errno != EAGAIN);
           printf("waiting... %lli\n", ++tick);
           sleep(1);
           continue;
         }
         tick = 0;
         message = strchr(message, ' ') + 1;
         if (!strcmp(message, "stop"))
           break;
         printf("\033[01m%s\033[21m\n", message);
       }
       t (bus_poll_stop(&bus));
       bus_close(&bus);
       return 0;

     fail:
       perror("poll");
       bus_poll_stop(&bus);
       bus_close(&bus);
       return 1;
     }

./write.c
.........

     #include <bus.h>
     #include <stdio.h>
     #include <unistd.h>
     #include <stdint.h>

     #define t(stmt)  if (stmt) goto fail

     static char message[BUS_MEMORY_SIZE];

     int main(int argc, char *argv[])
     {
       bus_t bus;
       if (argc < 2) {
         fprintf(stderr, "%s: USAGE: %s message\n", argv[0], argv[0]);
         return 2;
       }
       sprintf(message, "0 %s", argv[1]);
       t (bus_open(&bus, "/tmp/example-bus", BUS_WRONLY));
       t (bus_write(&bus, message, BUS_NOWAIT));
       bus_close(&bus);
       return 0;

     fail:
       perror("write");
       bus_close(&bus);
       return 1;
     }

Daemon-depedencies
==================

TODO

GNU Free Documentation License
******************************

     [file fdl.texinfo not included]