msg_send_libos.c 1.9 KB

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