1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
|
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/file.h>
#include <termio.h>
#define STR_SIZE 256
static const char* EOL_CMD = "\n";
static const char* DEFAULT_CMD = "ls -l";
static bool SetEcho(int dev_tty, bool enable)
{
struct termio termBuf;
ioctl(dev_tty, TCGETA, &termBuf);
if (enable) {
termBuf.c_lflag |= ECHO; // Enable echo
} else {
termBuf.c_lflag &= ~ECHO; // Don't echo
}
ioctl(dev_tty, TCSETAW, &termBuf);
return true;
}
static bool SendCMDToTTY(const char* cmd)
{
int dev_tty = open("/dev/tty", O_RDWR);
if (!dev_tty) {
return false;
}
SetEcho(dev_tty, false);
size_t cmdSize = strlen(cmd);
for (size_t i = 0; i < cmdSize; i++) {
ioctl(dev_tty, TIOCSTI, &cmd[i]);
}
SetEcho(dev_tty, true);
close(dev_tty);
return true;
}
int main(int argc, char* argv[])
{
char sys_cmd[STR_SIZE];
memset(sys_cmd, NULL, STR_SIZE);
for (int i = 1; i < argc; i++) {
sprintf(sys_cmd, "%s%s%s", sys_cmd, i == 1 ? "" : " ", argv[i]);
}
if (argc == 1) {
sprintf(sys_cmd, "%s", DEFAULT_CMD);
}
sprintf(sys_cmd, "%s%s", sys_cmd, EOL_CMD);
sys_cmd[STR_SIZE - 1] = NULL;
if (!SendCMDToTTY(sys_cmd)) {
perror("Error while sending the command to TTY");
}
return 0;
}
|