1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| #include <stdio.h> #include <stdlib.h> #include <sys/msg.h> #include <getopt.h> #include <string.h>
struct msg_buffer { long mtype; char mtext[1024]; };
int main(int argc, char *argv[]) { int next_option; const char* const short_options = "i:t:m:"; const struct option long_options[] = { { "id", 1, NULL, 'i'}, { "type", 1, NULL, 't'}, { "message", 1, NULL, 'm'}, { NULL, 0, NULL, 0 } }; int messagequeueid = -1; struct msg_buffer buffer; buffer.mtype = -1; int len = -1; char * message = NULL; do { next_option = getopt_long (argc, argv, short_options, long_options, NULL); switch (next_option) { case 'i': messagequeueid = atoi(optarg); break; case 't': buffer.mtype = atol(optarg); break; case 'm': message = optarg; len = strlen(message) + 1; if (len > 1024) { perror("message too long."); exit(1); } memcpy(buffer.mtext, message, len); break; default: break; } }while(next_option != -1);
if(messagequeueid != -1 && buffer.mtype != -1 && len != -1 && message != NULL){ if(msgsnd(messagequeueid, &buffer, len, IPC_NOWAIT) == -1){ perror("fail to send message."); exit(1); } } else { perror("arguments error"); } return 0; }
|