Search code examples
cipcftok

Whats is purpose ftok in Message queues


I have started reading message queues one of the IPC mechanism on Linux .But at very first step I have some very basic questions.

  1. Use of ftok() to generate unique ID (key) and what is unique ID which is to be generated.

  2. Can't we use simple a number to get our keys rather than using ftok()?

  3. What is the purpose of the argument key in the msget function?

    #include "sys/msg.h"
    key = ftok("/home/beej/somefile", 'b');
    msqid = msgget(key, 0666 | IPC_CREAT);
    
  4. What is the difference between msqid and key?


Solution

  • The ftok function creates a sort of identifier to be used with the System V IPC functions (semget, shmget, msgget). Think of it like a filedescriptor: when you open a file, you pass a path to open and get a number in return that is then used for read and write to identify the file. The ftok function serves a similar purpose, but while the filedescriptor's scope is limited to just the process that called open (and its children), the ftok token is valid across the system.

    The reason for the system scope is that you want two or more independent processes to have access to the same IPC resources. So if you have two programs, both of which execute key = ftok("/home/beej/somefile", 'b');, both will get the same token and can therefor access the same resources (semaphores, shared memory, message queues). That's the whole point of Inter Process Communication.

    You cannot just use a "simple number" as you don't know whether the token might be for example an index to an system-internal table or something. In other words, you don't know how that token is used internally so you do need to use ftok.

    The man page says: "The specified path must specify an existing file that is accessible to the calling process or the call will fail. Also, note that links to files will return the same key, given the same id." From this I assume that at least some ftok implementations create the token by looking up the inode number of the file specified by path and combine it with the second argument to create the token. The second argument exists simply so you can create a bunch of IPC resources (like several semaphores to protect different resources).

    As for the difference of key_t (the value returned by ftok) and the value retured by msgget: the former gives you access to a bunch of IPC resources (semaphore, shared memory and message queue), while the later identifies a specific message queue.