msg_send.libos.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <sys/types.h>
  6. #include <sys/ipc.h>
  7. #include <sys/msg.h>
  8. #include <sys/time.h>
  9. #include <sys/wait.h>
  10. #include <shim_unistd.h>
  11. #define PAYLOAD_SIZE 4
  12. struct msgbuf {
  13. long mtype;
  14. char mtext[PAYLOAD_SIZE];
  15. };
  16. #define TEST_TIMES 1000
  17. #define DO_BENCH 1
  18. int msqid;
  19. /* server always sends messages */
  20. void server (void)
  21. {
  22. struct timeval tv1, tv2;
  23. struct msgbuf buf;
  24. int i;
  25. buf.mtype = 1;
  26. gettimeofday(&tv1, NULL);
  27. for (i = 0 ; i < TEST_TIMES ; i++) {
  28. if (msgsnd(msqid, &buf, PAYLOAD_SIZE, 0) < 0) {
  29. perror("msgsnd");
  30. exit(1);
  31. }
  32. #ifndef DO_BENCH
  33. printf("Message: \"%s\" sent\n", buf.mtext);
  34. #endif
  35. }
  36. msgpersist(msqid, MSGPERSIST_STORE);
  37. gettimeofday(&tv2, NULL);
  38. printf("time spent on %d msgsnd: %llu microsecond\n",
  39. TEST_TIMES,
  40. (tv2.tv_sec * 1000000ull + tv2.tv_usec) -
  41. (tv1.tv_sec * 1000000ull + tv1.tv_usec));
  42. }
  43. /* client always sends messages */
  44. void client (void)
  45. {
  46. struct timeval tv1, tv2;
  47. struct msgbuf buf;
  48. int ret;
  49. gettimeofday(&tv1, NULL);
  50. msgpersist(msqid, MSGPERSIST_LOAD);
  51. for (int i = 0 ; i < TEST_TIMES ; i++) {
  52. if ((ret = msgrcv(msqid, &buf, PAYLOAD_SIZE, 1, 0)) < 0) {
  53. perror("msgrcv");
  54. exit(1);
  55. }
  56. #ifndef DO_BENCH
  57. buf.mtext[ret] = 0;
  58. printf("Client received: \"%s\"\n", buf.mtext);
  59. #endif
  60. }
  61. gettimeofday(&tv2, NULL);
  62. printf("time spent on %d msgrcv: %llu microsecond\n",
  63. TEST_TIMES,
  64. (tv2.tv_sec * 1000000ull + tv2.tv_usec) -
  65. (tv1.tv_sec * 1000000ull + tv1.tv_usec));
  66. msgctl(msqid, IPC_RMID, NULL);
  67. }
  68. int main (int argc, char ** argv)
  69. {
  70. if ((msqid = msgget(IPC_PRIVATE, 0600|IPC_CREAT)) < 0) {
  71. perror("msgget");
  72. exit(1);
  73. }
  74. server();
  75. client();
  76. return 0;
  77. }