tst-msgctl.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <time.h>
  5. #include <sys/ipc.h>
  6. #include <sys/msg.h>
  7. #include <sys/types.h>
  8. // Define the message structure
  9. struct msg_buffer {
  10. long msg_type;
  11. char msg_text[100];
  12. };
  13. void print_queue_times(int msgid) {
  14. struct msqid_ds info;
  15. if (msgctl(msgid, IPC_STAT, &info) == -1) {
  16. perror("msgctl IPC_STAT failed");
  17. exit(1);
  18. }
  19. printf("Last send time (msg_stime): %s", ctime(&info.msg_stime));
  20. printf("Last recv time (msg_rtime): %s", ctime(&info.msg_rtime));
  21. printf("Last change time (msg_ctime): %s", ctime(&info.msg_ctime));
  22. }
  23. int main() {
  24. key_t key;
  25. int msgid;
  26. struct msqid_ds buf;
  27. // Generate a unique key
  28. key = ftok("progfile", 65);
  29. // Create a message queue and return its id
  30. msgid = msgget(key, 0666 | IPC_CREAT);
  31. if (msgid == -1) {
  32. perror("msgget failed");
  33. exit(EXIT_FAILURE);
  34. }
  35. // Prepare message to send
  36. struct msg_buffer message;
  37. message.msg_type = 1;
  38. strcpy(message.msg_text, "Hello from message queue!");
  39. // Send the message
  40. if (msgsnd(msgid, &message, sizeof(message.msg_text), 0) < 0) {
  41. perror("msgsnd failed");
  42. exit(EXIT_FAILURE);
  43. }
  44. printf("Message sent: %s\n", message.msg_text);
  45. print_queue_times(msgid); // Show msg_stime after sending
  46. // Get information about the message queue
  47. if (msgctl(msgid, IPC_STAT, &buf) == -1) {
  48. perror("msgctl - IPC_STAT failed");
  49. exit(EXIT_FAILURE);
  50. }
  51. // Print some info from the msqid_ds structure
  52. printf("Message queue ID: %d\n", msgid);
  53. // Receive the message
  54. struct msg_buffer received;
  55. if (msgrcv(msgid, &received, sizeof(received.msg_text), 1, 0) < 0) {
  56. perror("msgrcv failed");
  57. exit(EXIT_FAILURE);
  58. }
  59. printf("Message received: %s\n", received.msg_text);
  60. print_queue_times(msgid); // Show msg_stime after receiving
  61. // Remove the message queue
  62. if (msgctl(msgid, IPC_RMID, NULL) == -1) {
  63. perror("msgctl - IPC_RMID failed");
  64. exit(EXIT_FAILURE);
  65. }
  66. printf("Message queue removed successfully.\n");
  67. return 0;
  68. }