每个进程都有一个/dev/tty的设备,使用它进行读写,可以预防重定向
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
char *msg[] = {"a --apple",
"b --blue",
"q --quit",
NULL
};
void getoption(char *greet, FILE *in, FILE *out);
int main(int agrc, char *argv[])
{
FILE *input;
FILE *output;
if(!isatty(STDOUT_FILENO))
{
fprintf(stderr, "your lose termninate\n");
}
input = fopen("/dev/tty", "r");
output = fopen("/dev/tty", "w");
if(!input || !output)
{
fprintf(stderr, "open(/dev/tty) failed\n");
}
getoption("how are you", input, output);
return 0;
}
void getoption(char *greet, FILE *in, FILE *out)
{
char ch;
char **p;
int choose = 0;
do
{
fprintf(out, "%s\n", greet);
p = msg;
while(p && *p)
{
fprintf(out, "%s\n", *p);
p++;
}
do
{
ch = fgetc(in);
}while(ch == '\n');
p = msg;
while(p && *p)
{
if(ch == *msg[2])
{
choose = 1;
break;
}
p++;
}
if(!choose)
{
fprintf(out, "your enter a error command\n");
}
}while(!choose);
}