sprog.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #include <stdarg.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <errno.h>
  5. #include <stdio.h>
  6. #include <unistd.h>
  7. #include <sprog.h>
  8. void sprog_process(const struct sprog_family *fam, void *arg, int nstdin, int nstdout);
  9. void sprog_error(const char *text, ...) {
  10. va_list l;
  11. va_start(l, text);
  12. vfprintf(stderr, text, l);
  13. va_end(l);
  14. }
  15. void sprog_sleep(int msec) {
  16. usleep(msec * 1000);
  17. }
  18. void sprog_communicate(const struct sprog_family *fam, const char *port, int baud) {
  19. int pstdin[2];
  20. int pstdout[2];
  21. int pid;
  22. void *arg;
  23. struct serial_device dev;
  24. serial_open(&dev, port, baud);
  25. arg = fam->setup(&dev);
  26. pipe(pstdin);
  27. pipe(pstdout);
  28. pid = fork();
  29. if(pid<0)
  30. sprog_error("Unable to fork: %s\n", strerror(errno));
  31. else {
  32. if(pid==0) {
  33. close(pstdin[0]);
  34. close(pstdout[1]);
  35. serial_communicate(&dev, pstdout[0], pstdin[1]);
  36. fam->close(arg);
  37. } else {
  38. close(pstdin[1]);
  39. close(pstdout[0]);
  40. sprog_process(fam, arg, pstdin[0], pstdout[1]);
  41. }
  42. }
  43. }
  44. void sprog_process(const struct sprog_family *fam, void *arg, int nstdin, int nstdout) {
  45. dup2(nstdin, 0);
  46. dup2(nstdout, 1);
  47. fam->init(arg);
  48. exit(0);
  49. }