Turning off echoing tends to be platform specific. Under System V Unix, you must manipulate the terminal driver. The following code doesn't do quite what you request. It gets one character from the terminal driver, but it illustrates turning off echoing.
/* ret_char.c. Unix System V dependent.
* This function is designed to return the ascii value of a
* single character * as long as it's alphanumeric, an interrupt,
* control-c or a Carriage Return. This function only accepts
* an alphanumeric, an interrupt or control-c.
*
* 1. Save original terminal settings.
* 2. Turn off canonial mode and echoing.
* 3. Get the character.
* 4. Reset the original terminal settings.
* 5. Return the character.
*
* Use this in a shell script as such:
* achar=`ret_char`
* echo "achar is: "$achar
*/
int ret_char()
{
struct termio tsave, chgit;
int c;
/* save original terminal settings */
if(ioctl(0, TCGETA, &tsave) == -1)
{
perror("bad term setting"
exit(1);
}
chgit = tsave;
/* turn off canonial mode and echoing */
chgit.c_lflag &= ~(ICANON|ECHO);
chgit.c_cc[VMIN] = 1;
chgit.c_cc[VTIME] = 0;
while (1)
{ /* break when an alphanumeric, interrupt,
control-c, CR is pressed */
c = getchar();
/* CR is ascii value 13, interrupt is -1, control-c is 3 */
if(isalnum(c) || c == '\r' || c == '\n' || c == '\b'
|| c == -1 || c == 3)
break;
}
/* reset to original terminal settings */
if(ioctl(0, TCSETA, &tsave) == -1)
{
perror("can't reset original setting"
exit(1);
}
/* return the character */
return(c);
}
Although I've never tried it, I don't think it'll work.
If memory serves me correctly, the system command spawns another shell, so I'm not certain that when the system command returns that the terminal driver changes are reflected in the parent.
Also, system calls also can be terribly inefficent.
Abnormal terminations can also leave your terminal in a undesired state.
Actually, it does work, I just really like to avoid using the system call. I think I'll go with your original suggestion and try to mock with the terminal driver using <termio.h>.
You learn something new every day. I think your decision to change the terminal driver is correct. BTW, what I know about the terminal driver, I learned from a book by David Curry, "Using C on the Unix System".
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.