sprog.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 <sys/select.h>
  8. #include <sprog.h>
  9. void sprog_process(const struct sprog_family *fam, void *arg, int nstdin, int nstdout);
  10. void sprog_error(const char *text, ...) {
  11. va_list l;
  12. va_start(l, text);
  13. vfprintf(stderr, text, l);
  14. va_end(l);
  15. }
  16. void sprog_sleep(int msec) {
  17. usleep(msec * 1000);
  18. }
  19. void sprog_communicate(const struct sprog_family *fam, const char *port, int baud) {
  20. int pstdin[2];
  21. int pstdout[2];
  22. int pid;
  23. void *arg;
  24. struct serial_device dev;
  25. serial_open(&dev, port, baud);
  26. arg = fam->setup(&dev);
  27. pipe(pstdin);
  28. pipe(pstdout);
  29. pid = fork();
  30. if(pid<0)
  31. sprog_error("Unable to fork: %s\n", strerror(errno));
  32. else {
  33. if(pid==0) {
  34. close(pstdin[0]);
  35. close(pstdout[1]);
  36. serial_communicate(&dev, pstdout[0], pstdin[1]);
  37. fam->close(arg);
  38. } else {
  39. close(pstdin[1]);
  40. close(pstdout[0]);
  41. sprog_process(fam, arg, pstdin[0], pstdout[1]);
  42. }
  43. }
  44. }
  45. int sprog_waitdata(int timeout) {
  46. fd_set read_set;
  47. struct timeval tval;
  48. FD_ZERO(&read_set);
  49. FD_SET(1, &read_set);
  50. tval.tv_sec = timeout/1000;
  51. tval.tv_usec = (timeout%1000)*1000;
  52. if(select(1+1, &read_set, NULL, NULL, &tval)!=1)
  53. return 0;
  54. return 1;
  55. }
  56. void sprog_process(const struct sprog_family *fam, void *arg, int nstdin, int nstdout) {
  57. dup2(nstdin, 0);
  58. dup2(nstdout, 1);
  59. fam->init(arg);
  60. exit(0);
  61. }