echotty.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include <stdlib.h>
  2. #include <fcntl.h>
  3. #include <sys/stat.h>
  4. #include <sys/ioctl.h>
  5. #include <string.h>
  6. #include <unistd.h>
  7. /*
  8. * http://www.humbug.in/2010/utility-to-send-commands-or-data-to-other-terminals-ttypts/
  9. */
  10. void print_help(char *prog_name) {
  11. printf("Usage: %s [-n] DEVNAME COMMAND\n", prog_name);
  12. printf("Usage: '-n' is an optional argument if you want to push a new line at the end of the text\n");
  13. printf("Usage: Will require 'sudo' to run if the executable is not setuid root\n");
  14. exit(1);
  15. }
  16. int main (int argc, char *argv[]) {
  17. char *cmd, *nl = "\n";
  18. int i, fd;
  19. int devno, commandno, newline;
  20. int mem_len;
  21. devno = 1; commandno = 2; newline = 0;
  22. if (argc < 3) {
  23. print_help(argv[0]);
  24. }
  25. if (argc > 3 && argv[1][0] == '-' && argv[1][1] == 'n') {
  26. devno = 2; commandno = 3; newline=1;
  27. } else if (argc > 3 && argv[1][0] == '-' && argv[1][1] != 'n') {
  28. printf("Invalid Option\n");
  29. print_help(argv[0]);
  30. }
  31. fd = open(argv[devno],O_RDWR);
  32. if(fd == -1) {
  33. perror("open DEVICE");
  34. exit(1);
  35. }
  36. mem_len = 0;
  37. for ( i = commandno; i < argc; i++ ) {
  38. mem_len += strlen(argv[i]) + 2;
  39. if ( i > commandno ) {
  40. cmd = (char *)realloc((void *)cmd, mem_len);
  41. } else { //i == commandno
  42. cmd = (char *)malloc(mem_len);
  43. }
  44. strcat(cmd, argv[i]);
  45. strcat(cmd, " ");
  46. }
  47. if (newline == 0)
  48. usleep(225000);
  49. for (i = 0; cmd[i]; i++)
  50. ioctl (fd, TIOCSTI, cmd+i);
  51. if (newline == 1)
  52. ioctl (fd, TIOCSTI, nl);
  53. close(fd);
  54. free((void *)cmd);
  55. exit (0);
  56. }