cttyhack.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Licensed under GPLv2
  4. *
  5. * Copyright (c) 2007 Denys Vlasenko <vda.linux@googlemail.com>
  6. */
  7. #include "libbb.h"
  8. /* From <linux/vt.h> */
  9. struct vt_stat {
  10. unsigned short v_active; /* active vt */
  11. unsigned short v_signal; /* signal to send */
  12. unsigned short v_state; /* vt bitmask */
  13. };
  14. enum { VT_GETSTATE = 0x5603 }; /* get global vt state info */
  15. /* From <linux/serial.h> */
  16. struct serial_struct {
  17. int type;
  18. int line;
  19. unsigned int port;
  20. int irq;
  21. int flags;
  22. int xmit_fifo_size;
  23. int custom_divisor;
  24. int baud_base;
  25. unsigned short close_delay;
  26. char io_type;
  27. char reserved_char[1];
  28. int hub6;
  29. unsigned short closing_wait; /* time to wait before closing */
  30. unsigned short closing_wait2; /* no longer used... */
  31. unsigned char *iomem_base;
  32. unsigned short iomem_reg_shift;
  33. unsigned int port_high;
  34. unsigned long iomap_base; /* cookie passed into ioremap */
  35. int reserved[1];
  36. };
  37. int cttyhack_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  38. int cttyhack_main(int argc UNUSED_PARAM, char **argv)
  39. {
  40. int fd;
  41. char console[sizeof(int)*3 + 16];
  42. union {
  43. struct vt_stat vt;
  44. struct serial_struct sr;
  45. char paranoia[sizeof(struct serial_struct) * 3];
  46. } u;
  47. if (!*++argv) {
  48. bb_show_usage();
  49. }
  50. strcpy(console, "/dev/tty");
  51. if (ioctl(0, TIOCGSERIAL, &u.sr) == 0) {
  52. /* this is a serial console */
  53. sprintf(console + 8, "S%d", u.sr.line);
  54. } else if (ioctl(0, VT_GETSTATE, &u.vt) == 0) {
  55. /* this is linux virtual tty */
  56. sprintf(console + 8, "S%d" + 1, u.vt.v_active);
  57. }
  58. if (console[8]) {
  59. fd = xopen(console, O_RDWR);
  60. //bb_error_msg("switching to '%s'", console);
  61. dup2(fd, 0);
  62. dup2(fd, 1);
  63. dup2(fd, 2);
  64. while (fd > 2) close(fd--);
  65. /* Some other session may have it as ctty. Steal it from them */
  66. ioctl(0, TIOCSCTTY, 1);
  67. }
  68. BB_EXECVP(argv[0], argv);
  69. bb_perror_msg_and_die("cannot exec '%s'", argv[0]);
  70. }