C shell program

  1. I've have to write a shell program that accepts Ctrl+T (in linux os in c language) and should print out the current time and date to the screen. I've written the following code but i've to type ^T individual rather than pressing ctrl+T(^T) to get the output. :

  2. How do i make the shell program to react when i press ctrl+T without having to press enter. For the following code which i wrote requires me to press enter to execute the command

#include<stdio.h>
#include<time.h>
#include<unistd.h>
#include<string.h>
#include<unistd.h>
#include<stdlib.h>

int main(void){
		
	time_t t;
	char buffer[100];
	int count;
	
	printf("My Prompt$: ");
	fflush(stdout);
	
	for(;;){
		count = read(0,buffer,99);
		buffer[count] = '\0';
		
		if(strncmp(buffer,"^T",2)==0){
			time(&t);
			printf("%s\n",ctime(&t));
		}
		if(strncmp(buffer,"exit",4)==0){
			exit(0);
		}
		printf("My Promts$ : ");
		fflush(stdout);
	}	
}

Output:
[zorro@localhost Desktop]$ gcc hw8.c
[zorro@localhost Desktop]$ ./a.out
My Prompt$: ^T // have to type ^T
Tue Apr 3 14:47:10 2018

My Promts$ : ^T // when i pressed ctrl+T & have to press enter
My Promts$ : ^T
My Promts$ : exit
[zorro@localhost Desktop]$

  1. Assumption University, Bangkok, Thailand, Wanchat.C, CE4207

When you read the stdin with read() as you do it you basically read linewise. You have some input field, where you can type and edit some text and you finally press <enter> to submit it - quite the same way you enter commands in the shell.

When you want to intercept single characters you need to use the getch() function or one of its variations ( getch() , getchar() , getche() ).

I hope this helps.

bakunin

In addition to using functions that get characters (rather than lines) from a file, you'll also need to put the input file descriptor into raw (rather than cooked) input mode if you want to read characters from a terminal device without waiting for a full line to be entered. Look at the man pages for tcgetattr() , tcsetattr() , and termios.h to see how to do this.