svmsg/svmsg_send.cThis is svmsg/svmsg_send.c (Listing 46-2, page 941), 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_send.c + + Usage: svmsg_send [-n] msqid msg-type [msg-text] + + Experiment with the msgsnd() system call to send messages to a + System V message queue. + + See also svmsg_receive.c. +*/ #include <sys/types.h> #include <sys/msg.h> #include "tlpi_hdr.h" #define MAX_MTEXT 1024 struct mbuf { long mtype; /* Message type */ char mtext[MAX_MTEXT]; /* Message body */ }; static void /* Print (optional) message, then usage description */ usageError(const char *progName, const char *msg) { if (msg != NULL) fprintf(stderr, "%s", msg); fprintf(stderr, "Usage: %s [-n] msqid msg-type [msg-text]\n", progName); fprintf(stderr, " -n Use IPC_NOWAIT flag\n"); exit(EXIT_FAILURE); } int main(int argc, char *argv[]) { int msqid, flags, msgLen; struct mbuf msg; /* Message buffer for msgsnd() */ int opt; /* Option character from getopt() */ /* Parse command-line options and arguments */ flags = 0; while ((opt = getopt(argc, argv, "n")) != -1) { if (opt == 'n') flags |= IPC_NOWAIT; else usageError(argv[0], NULL); } if (argc < optind + 2 || argc > optind + 3) usageError(argv[0], "Wrong number of arguments\n"); msqid = getInt(argv[optind], 0, "msqid"); msg.mtype = getInt(argv[optind + 1], 0, "msg-type"); if (argc > optind + 2) { /* 'msg-text' was supplied */ msgLen = strlen(argv[optind + 2]) + 1; if (msgLen > MAX_MTEXT) cmdLineErr("msg-text too long (max: %d characters)\n", MAX_MTEXT); memcpy(msg.mtext, argv[optind + 2], msgLen); } else { /* No 'msg-text' ==> zero-length msg */ msgLen = 0; } /* Send message */ if (msgsnd(msqid, &msg, msgLen, flags) == -1) errExit("msgsnd"); 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.