NachOS/code/userprog/consoledriver.cc
2021-11-19 14:15:32 +01:00

93 lines
2 KiB
C++

#ifdef CHANGED
#include "copyright.h"
#include "system.h"
#include "consoledriver.h"
#include "synch.h"
static Semaphore *readAvail;
static Semaphore *writeDone;
static Semaphore *m_PutChar;
static Semaphore *m_GetChar;
static void ReadAvailHandler(void *arg) { (void) arg; readAvail->V(); }
static void WriteDoneHandler(void *arg) { (void) arg; writeDone->V(); }
ConsoleDriver::ConsoleDriver(const char *in, const char *out)
{
readAvail = new Semaphore("read avail", 0);
writeDone = new Semaphore("write done", 0);
console = new Console (in, out, ReadAvailHandler, WriteDoneHandler, NULL);
// Add these semaphores because we had problems with threads
// Assert error on putBusy
m_PutChar = new Semaphore("PutChar", 1);
m_GetChar = new Semaphore("GetChar", 1);
}
ConsoleDriver::~ConsoleDriver()
{
delete console;
delete writeDone;
delete readAvail;
delete m_PutChar;
delete m_GetChar;
}
void ConsoleDriver::PutChar( int ch)
{
m_PutChar->P();
console->TX(ch);
writeDone->P();
m_PutChar->V();
}
int ConsoleDriver::GetChar()
{
m_GetChar->P();
readAvail->P();
int ch = console->RX();
m_GetChar->V();
return ch;
}
void ConsoleDriver::PutString(const char s[])
{
int i = 0;
while (*(s+i) != '\0')
{
PutChar(*(s+i));
i++;
}
}
void ConsoleDriver::GetString(char * s, int n)
{
int i;
for ( i = 0; i < n; i++){
char c = GetChar();
DEBUG('s', "consoledriver->getstring keycode:%d, position:%d\n", (int)c, i);
if ( c == '\0' || c == '\n' || c == EOF) {
break;
}
*(s+i) = c;
}
*(s+i) = '\0';
}
void ConsoleDriver::PutInt(int n)
{
char *buffer = new char[MAX_STRING_SIZE];
snprintf(buffer,MAX_STRING_SIZE,"%d",n);
DEBUG('s', "consoledriver->PutInt buffer:%s\n", buffer);
PutString(buffer);
delete [] buffer;
}
void ConsoleDriver::GetInt(int * n)
{
char *buffer = new char[MAX_STRING_SIZE];
GetString(buffer,MAX_STRING_SIZE);
sscanf(buffer, "%d", n);
delete [] buffer;
}
#endif // CHANGED