IPC Facilities Key

key_t key is a 32-bit identifier associated with an #Interprocess Communication (IPC) object on a #unix system. It can be obtained from the function ftok() imported from sys/types.h and sys/ipc.h that maps a file’s pathname and an 8-bit integer into a key. The creation of key is shown as below:

                  // pathname
key_t key = ftok("/tmp", 'S');
                         // 8-bit integer

If the flag passed to the IPC object System Call (#Message Queue, semaphore, and share memory) are IPC_CREAT and IPC_EXCL (exclusive), there is an additional need to check against the error number EEXIST which indicates that the IPC object has already existed.

If duplication is undesired, we could use IPC_PRIVATE as the IPC key instead so that it guarantees to create a unique IPC object.

Links to this page
  • TTP3121 Chapter 7: Inter Process Communication Part 2
  • Semaphore in System V

    We can access (with flag values of 0) or create (with flag IPC_CREAT) a semaphore with semget() System Call# with parameters of IPC Facilities Key# the number of semaphores to be created, and the flags (including semaphore’s permission). semop() is used to release (increment) and obtain (decrement) semaphore or test for zero. It includes using a sembuf struct to specify the operation to be performed on each semaphore in the semaphore set identified by its ID. The detail are shown below:

  • Name Space
  • Message Queue

    We can access (with flag values of 0) and/or create a Message Queue (with IPC_CREAT flag) by msgget() to gain the message queue ID by passing the associated IPC Facilities Key#. To get or alter the msqid_ds, we can utilise msgctl() system call by passing the message queue ID and command flag (IPC_STAT to get msqid_ds, IPC_SET to alter msg_perm.uid, msg_perm.gid, msg_perm.mode and msg_qbytes) needed. Sending message to the message queue could be done by calling msgsnd() with parameters of target message queue’s ID, a pointer to a message structure (shown below), the length of the message, and a flag. If msgsnd()’s flag is set as IPC_NOWAIT, it makes the call to return immediately if there is no room from the message queue to accept new messages. Receiving message from the message queue could be done by calling msgrcv() with almost identical parameters as msgsnd() except it needs an additional type long variable. A more detail explanation on how msgrcv() handles type will be explored below. By default, msgrcv() is in blocking state, meaning it will either wait until a message is available, the message queue is removed or interrupted by signal. If IPC_NOWAIT is set, then msgrcv() will return immediately with errno set as ENOMSG if the requested type is not on the queue. To remove a message queue, call msgctl() with the flag IPC_RMID.

  • Interprocess Communication (IPC)

    Note: See IPC Facilities Key#.

#operating-system #unix