I have just encountered a problem which I couldn't found the reason. The code works as Below:
- There is a while loop which does a lot of stuff in the middle (Does not even written), and has a non-blocking IO to receive the end process command (which is a string).
- At any time, a user could come and wants to finish the process. He/She would press some keys and then press the [Enter] button.
- After select find out there is an input, it uses the input string and evaluates with the EXIT string and end the process.
Now the problem is when I use the exitFlag string as the termination key it just don't accept it and keeps writing <the printf() statement> until i hit cntrl+c. I have tried scanf(), fputs(), fread() to recieve input string from stdin and also used fflush(stdin) and fflush(stdout) to clear the std buffers.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
int main()
{
fd_set s;
struct timeval timeout;
timeout.tv_sec = 3;
timeout.tv_usec = 0;
char exitFlag[10];
int sFlag;
printf("Enter \"EXIT\" to End the Process\n");
while (1)
{
fflush(stdin); fflush(stdout);
FD_ZERO(&s);
FD_SET(STDIN_FILENO, &s);
timeout.tv_sec = 3; timeout.tv_usec = 0;
sFlag = select(STDIN_FILENO+1, &s, NULL, NULL, &timeout);
printf("%d: ", sFlag);
if (sFlag < 0) _exit(0);
else if (sFlag == 0)
{
printf("-\n");
fflush(stdin); fflush(stdout);
}
else
{
fflush(stdin); fflush(stdout);
scanf("%[^\n]s", &exitFlag); // fgets( exitFlag, 10, stdin); // fread( exitFlag, 10, 1 ,stdin);
printf("You have Pressed %s, Enter \"EXIT\" to End the Process: ", exitFlag);
printf("%s\n", exitFlag);
if ( memcmp(&exitFlag, "EXIT", 4) == 0 ) break;
}
}
return 0;
}
Ironically, I don't encounter similar problem when using char as the termination key input rather than string. I would be very thankful if someone explains where I made mistake in the IO or any other place.
I have also reviewed prior questions carefully but they had seemed to work with a single keyboard press which was not safe for common use!
include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
int main()
{
fd_set s;
struct timeval timeout;
timeout.tv_sec = 3;
timeout.tv_usec = 0;
char exitFlag;
int sFlag;
while (1)
{
fflush(stdout);
FD_ZERO(&s);
FD_SET(STDIN_FILENO, &s);
timeout.tv_sec = 3; timeout.tv_usec = 0;
sFlag = select(STDIN_FILENO+1, &s, NULL, NULL, &timeout);
if (sFlag < 0) _exit(0);
else if (sFlag == 0)
{
fflush(stdout);
printf("-\n");
}
else
{
fflush(stdin);
scanf("%c", &exitFlag);
printf("You have Pressed %c, Press E to exit: ", exitFlag);
printf("%c\n", exitFlag);
fflush(stdout);
if ( exitFlag =='E' ) break;
}
}
return 0;
}