int main(int argc, char *argv[]) { struct mymsgbuf qbuf; char key_id[16]; key_t key; int msgid, type; unsigned short opperm; char cmd[MAX_SIZE] = { 0 }; printf ( "Message queues present in the system\n" ); system("ipcs -q"); printf( "\nEnter the desired key in hex (form: 0x0807633d, 0x0 for IPC_PRIVATE)\n or queue's id in decimal: "); scanf( "%15s", key_id); if ( sscanf( key_id, "0x%x", &key ) == 0 ) { // key_id represents an ID sscanf( key_id, "%d", &msgid ); printf( "\nmsgid = %d", msgid ); } else { // key_id is a key, otherwise msgid = msgget_wrapper( key ); if ( msgid == -1 ) syserr("msgget"); } printf( "\nmsgid = %d\n", msgid ); while (1) { fprintf(stderr, "\nChoose an action:\n"); fprintf(stderr, " (s)end <type> <messagetext>\n"); fprintf(stderr, " (r)ecv <type>\n"); fprintf(stderr, " (d)elete\n"); fprintf(stderr, " (m)ode <octal mode>\n"); fprintf(stderr, " (q)uit the application\n"); scanf("%s", cmd); switch(tolower(cmd[0])) { case 's': scanf("%d", &type); fgets(cmd, MAX_SIZE-1, stdin); send_message(msgid, &qbuf, type, cmd); break; case 'r': scanf("%d", &type); read_message(msgid, &qbuf, type); break; case 'd': remove_queue(msgid); break; case 'm': scanf("%ho", &opperm); change_queue_mode(msgid, opperm); break; case 'q': return 0; } } return 0 ; }
int main(int argc, char *argv[]) { key_t key; int msgqueue_id; struct mymsgbuf qbuf; if(argc == 1) usage(); /* Create unique key via call to ftok() */ key = ftok(".", 'm'); /* Open the queue - create if necessary */ if((msgqueue_id = msgget(key, IPC_CREAT|0660)) == -1) { perror("msgget"); exit(1); } switch(tolower(argv[1][0])) { case 's': send_message(msgqueue_id, (struct mymsgbuf *)&qbuf, atol(argv[2]), argv[3]); break; case 'r': read_message(msgqueue_id, &qbuf, atol(argv[2])); break; case 'd': remove_queue(msgqueue_id); break; case 'm': change_queue_mode(msgqueue_id, argv[2]); break; default: usage(); } return(0); }
int main(int argc, char *argv[]) { key_t key; int msgqueue_id; //消息队列标识符 struct mymsgbuf qbuf; if (argc == 1) usage(); /*create unique key via call to ftok()*/ key = ftok(".", 'm'); /*open the queue - create if necessary*/ if ((msgqueue_id = msgget(key, IPC_CREAT | 0660)) == -1) { perror("msgget"); exit(1); } /*关于argv[1][0]的解释来自:stackoverflow.com/questions/11757951/what-is-the-meaning-of-argv10(foreign Web) * as others have pointed out, argv[1] is the second string in the string array argv, * and strings are character arrays so argv[1][0] is the first character in the second * string. * that is(也就是说):it means the first character of the second string of argv. * */ switch (tolower(argv[1][0])) { case 's': send_message(msgqueue_id, (struct mymsgbuf *)&qbuf, atol(argv[2]), argv[3]); break; case 'r': read_message(msgqueue_id, &qbuf, atol(argv[2])); //atol:将字符串转换成长整型数 break; case 'd': remove_queue(msgqueue_id); break; case 'm': change_queue_mode(msgqueue_id, argv[2]); break; default: usage(); } return 0; }