msg_send.libos.c 2.1 KB

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