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.

60 lines
1.6KB

  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. * If "delayus" is specified, this will be the delay we wait between the moment
  14. * we write the "ping" and the moment where we fetch the "pong".
  15. */
  16. int main(int argc, char **argv)
  17. {
  18. int delayus = 1000;
  19. if (argc == 4) {
  20. delayus = atoi(argv[3]);
  21. } else if (argc != 3) {
  22. fprintf(stderr, "Usage: ./pingpong device fname [delayus] \n");
  23. return 1;
  24. }
  25. FILE *fp = fopen(argv[2], "r");
  26. if (!fp) {
  27. fprintf(stderr, "Can't open %s.\n", argv[2]);
  28. return 1;
  29. }
  30. int fd = ttyopen(argv[1]);
  31. unsigned char c;
  32. int returncode = 0;
  33. while (fread(&c, 1, 1, fp)) {
  34. putchar('.');
  35. fflush(stdout);
  36. write(fd, &c, 1);
  37. usleep(delayus); // let it breathe
  38. if (!mexpect(fd, c)) {
  39. // mismatch!
  40. unsigned int pos = ftell(fp);
  41. fprintf(stderr, "Mismatch at byte %d!\n", pos);
  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. if (fd > 0) {
  52. close(fd);
  53. }
  54. return returncode;
  55. }