Mirror of CollapseOS
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

57 lines
1.5KB

  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <fcntl.h>
  4. #include <unistd.h>
  5. #include "common.h"
  6. /* Sends the contents of `fname` to `device`, expecting every sent byte to be
  7. * echoed back verbatim. Compare every echoed byte with the one sent and bail
  8. * out if a mismatch is detected. When the whole file is sent, push a null char
  9. * to indicate EOF to the receiving end.
  10. *
  11. * It is recommended that you send contents that has gone through `ttysafe`.
  12. */
  13. int main(int argc, char **argv)
  14. {
  15. if (argc != 3) {
  16. fprintf(stderr, "Usage: ./pingpong device fname\n");
  17. return 1;
  18. }
  19. FILE *fp = fopen(argv[2], "r");
  20. if (!fp) {
  21. fprintf(stderr, "Can't open %s.\n", argv[2]);
  22. return 1;
  23. }
  24. int fd = open(argv[1], O_RDWR|O_NOCTTY|O_NONBLOCK);
  25. printf("Press a key...\n");
  26. getchar();
  27. unsigned char c;
  28. // empty the recv buffer
  29. while (read(fd, &c, 1) == 1) usleep(1000);
  30. int returncode = 0;
  31. while (fread(&c, 1, 1, fp)) {
  32. putchar('.');
  33. fflush(stdout);
  34. write(fd, &c, 1);
  35. usleep(1000); // let it breathe
  36. unsigned char c2;
  37. while (read(fd, &c2, 1) != 1); // read echo
  38. if (c != c2) {
  39. // mismatch!
  40. unsigned int pos = ftell(fp);
  41. fprintf(stderr, "Mismatch at byte %d! %d != %d.\n", pos, c, c2);
  42. returncode = 1;
  43. break;
  44. }
  45. }
  46. // To close the receiving loop on the other side, we send a straight null
  47. c = 0;
  48. write(fd, &c, 1);
  49. printf("Done!\n");
  50. fclose(fp);
  51. return returncode;
  52. }