svmsg/svmsg_create.cThis is svmsg/svmsg_create.c (Listing 46-1, page 938), an example from the book, The Linux Programming Interface. The source code file is copyright 2024, Michael Kerrisk, and is licensed under the GNU General Public License, version 3. This page shows the "distribution" or "book" version of the file (why are there two versions?), or the differences between the two versions. You can switch between the views using the tabs below. In the listing below, the names of Linux system calls and C library functions are hyperlinked to manual pages from the Linux man-pages project, and the names of functions implemented in the book are hyperlinked to the implementations of those functions.
|
/* svmsg_create.c Experiment with the use of msgget() to create a System V message queue. */ #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <sys/stat.h> #include "tlpi_hdr.h"
static void /* Print usage info, then exit */ usageError(const char *progName, const char *msg) { if (msg != NULL) fprintf(stderr, "%s", msg); fprintf(stderr, "Usage: %s [-cx] {-f pathname | -k key | -p} " "[octal-perms]\n", progName); fprintf(stderr, " -c Use IPC_CREAT flag\n"); fprintf(stderr, " -x Use IPC_EXCL flag\n"); fprintf(stderr, " -f pathname Generate key using ftok()\n"); fprintf(stderr, " -k key Use 'key' as key\n"); fprintf(stderr, " -p Use IPC_PRIVATE key\n"); exit(EXIT_FAILURE); }
int main(int argc, char *argv[]) { int numKeyFlags; /* Counts -f, -k, and -p options */ int flags, msqid, opt; unsigned int perms; long lkey; key_t key; /* Parse command-line options and arguments */ numKeyFlags = 0; flags = 0; while ((opt = getopt(argc, argv, "cf:k:px")) != -1) { switch (opt) { case 'c': flags |= IPC_CREAT; break; case 'f': /* -f pathname */ key = ftok(optarg, 1); if (key == -1) errExit("ftok"); numKeyFlags++; break; case 'k': /* -k key (octal, decimal or hexadecimal) */ if (sscanf(optarg, "%li", &lkey) != 1) cmdLineErr("-k option requires a numeric argument\n"); key = lkey; numKeyFlags++; break; case 'p': key = IPC_PRIVATE; numKeyFlags++; break; case 'x': flags |= IPC_EXCL; break; default: usageError(argv[0], "Bad option\n"); } } if (numKeyFlags != 1) usageError(argv[0], "Exactly one of the options -f, -k, " "or -p must be supplied\n"); perms = (optind == argc) ? (S_IRUSR | S_IWUSR) : getInt(argv[optind], GN_BASE_8, "octal-perms"); msqid = msgget(key, flags | perms); if (msqid == -1) errExit("msgget"); printf("%d\n", msqid); exit(EXIT_SUCCESS); }
Note that, in most cases, the programs rendered in these web pages are not free standing: you'll typically also need a few other source files (mostly in the lib/ subdirectory) as well. Generally, it's easier to just download the entire source tarball and build the programs with make(1). By hovering your mouse over the various hyperlinked include files and function calls above, you can see which other source files this file depends on.