sockpong.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. /*
  6. * File: sockpong.c
  7. *
  8. * Description:
  9. * This test runs in conjunction with the sockping test.
  10. * The sockping test creates a socket pair and passes one
  11. * socket to this test. Then the sockping test writes
  12. * "ping" to this test and this test writes "pong" back.
  13. * To run this pair of tests, just invoke sockping.
  14. *
  15. * Tested areas: process creation, socket pairs, file
  16. * descriptor inheritance.
  17. */
  18. #include "prerror.h"
  19. #include "prio.h"
  20. #include <stdio.h>
  21. #include <string.h>
  22. #include <stdlib.h>
  23. #define NUM_ITERATIONS 10
  24. int main(int argc, char **argv)
  25. {
  26. PRFileDesc *sock;
  27. PRStatus status;
  28. char buf[1024];
  29. PRInt32 nBytes;
  30. int idx;
  31. sock = PR_GetInheritedFD("SOCKET");
  32. if (sock == NULL) {
  33. fprintf(stderr, "PR_GetInheritedFD failed\n");
  34. exit(1);
  35. }
  36. status = PR_SetFDInheritable(sock, PR_FALSE);
  37. if (status == PR_FAILURE) {
  38. fprintf(stderr, "PR_SetFDInheritable failed\n");
  39. exit(1);
  40. }
  41. for (idx = 0; idx < NUM_ITERATIONS; idx++) {
  42. memset(buf, 0, sizeof(buf));
  43. nBytes = PR_Read(sock, buf, sizeof(buf));
  44. if (nBytes == -1) {
  45. fprintf(stderr, "PR_Read failed: (%d, %d)\n",
  46. PR_GetError(), PR_GetOSError());
  47. exit(1);
  48. }
  49. printf("pong process: received \"%s\"\n", buf);
  50. if (nBytes != 5) {
  51. fprintf(stderr, "pong process: expected 5 bytes but got %d bytes\n",
  52. nBytes);
  53. exit(1);
  54. }
  55. if (strcmp(buf, "ping") != 0) {
  56. fprintf(stderr, "pong process: expected \"ping\" but got \"%s\"\n",
  57. buf);
  58. exit(1);
  59. }
  60. strcpy(buf, "pong");
  61. printf("pong process: sending \"%s\"\n", buf);
  62. nBytes = PR_Write(sock, buf, 5);
  63. if (nBytes == -1) {
  64. fprintf(stderr, "PR_Write failed\n");
  65. exit(1);
  66. }
  67. }
  68. status = PR_Close(sock);
  69. if (status == PR_FAILURE) {
  70. fprintf(stderr, "PR_Close failed\n");
  71. exit(1);
  72. }
  73. return 0;
  74. }