WTS LastInputTime - c++

i'm trying to retrive the difference between CurrentTime and LastInputTime and comparing it to another value. CurrentTime is updating correctly but LastInputTime is always a constant value, i dont know why sometimes is 0 , sometimes is other constant value . Any help ?
void localSessions()
{
while (TRUE)
{
cout << "Risky local logon sessions :" << endl;
DWORD pCount;
PWTS_SESSION_INFO pSessionsInfo=new WTS_SESSION_INFO[MAX_SESSIONS];
WTSEnumerateSessionsA(WTS_CURRENT_SERVER_HANDLE, 0, 1, &pSessionsInfo, &pCount);
DWORD bytes;
for (auto it = 0; it < pCount; it++)
{
WTSINFOEX* ptr;
if (pSessionsInfo[it].State == WTSActive)
{
INT ret = WTSQuerySessionInformationA(WTS_CURRENT_SERVER_HANDLE, pSessionsInfo[it].SessionId, WTSSessionInfoEx, (LPSTR*)&ptr, &bytes);
if (ret != 0)
{
INT ret = Gambit::OS::Environment::GetOSVersion();
INT unlocked = 0, unknown = 0;
LONGLONG last_input = ptr->Data.WTSInfoExLevel1.CurrentTime.QuadPart - ptr->Data.WTSInfoExLevel1.LastInputTime.QuadPart;
cout << last_input << endl;
HANDLE token;
WTSQueryUserToken(pSessionsInfo[it].SessionId, &token);
ImpersonateLoggedOnUser(token);
BOOL active;
SystemParametersInfo(SPI_GETSCREENSAVERRUNNING, 0, &active, 0);
RevertToSelf();
if (!(ret >= 16 && ret <= 19))
{
if ((ptr->Data.WTSInfoExLevel1.SessionFlags & WTS_SESSIONSTATE_UNLOCK) != 0)
{
unlocked = 1;
}
}
else if (ret >= 16 && ret <= 19)
{
if ((ptr->Data.WTSInfoExLevel1.SessionFlags & WTS_SESSIONSTATE_LOCK) != 0)
{
unlocked = 1;
}
}
if (unlocked == 1 && active == FALSE && last_input > 500000000000)
{
cout << "Winstation name : " << ptr->Data.WTSInfoExLevel1.WinStationName << endl;
cout << "UserName name : " << ptr->Data.WTSInfoExLevel1.UserName << endl;
cout << "Domain name : " << ptr->Data.WTSInfoExLevel1.DomainName << endl;
}
cout << endl;
}
}
}
cout << endl << endl;
Sleep(1000);
}
}

LastInputTime is zero for a local session.
For a remote session, when there is no user input after last query of LastInputTime, it will keep unchanged. If there is a user input (like mouse move etc), LastInputTime will update to new time.
If you want to monitor local session user input time you can use GetLastInputInfo instead.

Related

Trying to convert a POSIX based system to Windows

I'm currently trying to convert a multithreaded LAN tic tac toe game so it compiles / works on my Windows system. I'm quite new to networking but I've managed to translate a lot of the system calls to Socket API calls however I am having trouble understanding how to convert the 'pthread' functions. Most of the questions I see online are asking how to compile it, but I want to change it instead of adding new libraries etc.
Can someone please shed some light on what exactly pthread does and how I can change it to compile in the native windows environment.
Thanks!
Main Function
pthread_mutex_t games_lock = PTHREAD_MUTEX_INITIALIZER;
int main() {
//Initialise Winsock
WSAData data;
WORD ver = MAKEWORD(2, 2);
int wsResult = WSAStartup(ver, &data);
if (wsResult != 0) {
std::cerr << "Can't start Winsock, Err #" << wsResult << endl;
}
// Signals used to kill the server gracefully
if (signal(SIGINT, sig_handler) == SIG_ERR)
{
perror("Can't catch SIGINT");
exit(1);
}
if (signal(SIGTERM, sig_handler) == SIG_ERR)
{
perror("Can't catch SIGTERM");
exit(1);
}
// Initialize the server and get the server's socket
server_sock = init_server();
int new_socket = 0;
// Infinitely accept clients and spawning threads
while (true)
{
// Wait for a client, and then accept
if ((new_socket = accept(server_sock, NULL, NULL)) < 0)
{
perror("Failed to accept client");
closesocket(server_sock);
exit(1);
}
cout << "New client connected" << endl;
// Spawn thread to handle the client
pthread_t threadid;
pthread_create(&threadid, NULL, handle_client, (void*)&new_socket);
}
return 0;
}
Client Handle Function
{
int client_sock = *(int*)arg;
char buffer[BUF_SIZE];
bool client_connected = true;
char temp = '\0';
int row = 0, col = 0;
int i = 0;
// Create the player
Player player(client_sock);
// Always handle the client
while (client_connected)
{
// Process commands or pass game data
if (player.GetMode() == COMMAND)
{
// Read a line of text or until the buffer is full
for (i = 0; (i < (BUF_SIZE - 1)) && temp != '\n' && client_connected; ++i)
{
// Receive a single character and make sure the client is still connected
if (recv(client_sock, &temp, 1, 0) == 0)
client_connected = false;
else
buffer[i] = temp;
}
// Reset temp so we don't get an infinite loop
temp = '\0';
buffer[i] = '\0';
buffer[i - 1] = '\0';
cout << "Received command \"" << buffer << "\" from " << player.GetName() << endl;
buffer[i - 1] = '\n';
// If there's an invalid command, tell the client
if (!ProcessCommand(buffer, player, client_connected))
SendStatus(player.GetSocket(), INVALID_CMD);
}
else if (player.GetMode() == INGAME)
{
// Get the game the player is a part of
pthread_mutex_lock(&games_lock);
auto game = find_if(game_list.begin(), game_list.end(),
[player](TTTGame* game) { return game->HasPlayer(player); });
auto end = game_list.end();
pthread_mutex_unlock(&games_lock);
// Something horrible has gone wrong
if (game == end)
cout << "Somehow Player " << player.GetName() << " isn't a part of a game but is INGAME" << endl;
else
{
StatusCode status;
client_connected = ReceiveStatus(player.GetSocket(), &status);
// If the player is still connected, then perform the move
if (client_connected)
{
switch (status)
{
case MOVE:
// Pass the row and column right along
ReceiveInt(player.GetSocket(), &row);
ReceiveInt(player.GetSocket(), &col);
cout << "Received moved from " << player.GetName()
<< ": row=" << row << ", col=" << col << endl;
SendStatus((*game)->GetOtherPlayer(player).GetSocket(), MOVE);
SendInt((*game)->GetOtherPlayer(player).GetSocket(), row);
client_connected = SendInt((*game)->GetOtherPlayer(player).GetSocket(), col);
cout << "Sent move to " << (*game)->GetOtherPlayer(player).GetName() << endl;
break;
case WIN:
cout << player.GetName() << " won a game against " << (*game)->GetOtherPlayer(player).GetName() << endl;
client_connected = false;
break;
case DRAW:
cout << player.GetName() << " tied against " << (*game)->GetOtherPlayer(player).GetName() << endl;
client_connected = false;
break;
default:
client_connected = SendStatus(player.GetSocket(), INVALID_CMD);
}
}
}
}
}
// The client disconnected on us D:
cout << "Player \"" << player.GetName() << "\" has disconnected" << endl;
DisconnectPlayer(player);
closesocket(client_sock);
WSACleanup();
return (void*)0;
}
These are just some examples of the code. I am happy to post more if needed.

Problem with array of class objects leads to crash

So I am making a textbased RPG and I wanted to have multiple enemy encounter at once. So I modified my function that determines whether an object of the class Monster, to fill in the Monster(s) into an array of the class monster and set the objects bool to true, as you can see here:
Monster * Map::checkRandomEncounter()
{
Monster* monster = new Monster[3];
for (int i = 0; i < 3; i++)
{
int roll = Random(0, 20);
if (roll <= 5)
{
//No encounter
return 0;
}
else if (roll > 6 && roll < 10)
{
monster[i] = Monster();
monster[i].giveID("Orc", 10, 8, 200, 100, 1, "Short Sword", 2, 7);
monster[i].isFilled();
std::cout << "You encounter an Orc!" << std::endl;
std::cout << "Prepare for battle!" << std::endl;
std::cout << std::endl;
}
else if (roll >= 11 && roll <= 15)
{
monster[i] = Monster();
monster[i].giveID("Goblin", 6, 6, 100, 75, 0, "Dagger", 1, 5);
monster[i].isFilled();
std::cout << "You encounter a Goblin!" << std::endl;
std::cout << "Prepare for battle!" << std::endl;
std::cout << std::endl;
}
else if (roll >= 16 && roll <= 19)
{
monster[i] = Monster();
monster[i].giveID("Ogre", 20, 12, 500, 200, 2, "Club", 3, 8);
monster[i].isFilled();
std::cout << "You encounter an Ogre!" << std::endl;
std::cout << "Prepare for battle!" << std::endl;
std::cout << std::endl;
}
else if (roll == 20)
{
monster[i] = Monster();
monster[i].giveID("Orc Lord",
25,
15,
2000,
1000,
5,
"Two Handed Sword",
5,
20);
monster[i].isFilled();
std::cout << "You encounter an Orc Lord!" << std::endl;
std::cout << "Prepare for battle!" << std::endl;
std::cout << std::endl;
}
}
return monster;
}
The function above will be called in my main function, which looks like this:
int main()
{
srand(time(0));
Map gameMap;
Player mainPlayer;
mainPlayer.createClass();
//Beginn adventure
bool done = false;
while (done == false)
{
// Each Loop Cycle outputs player pos and selection menu
gameMap.printPlayerPos();
int selection = 1;
std::cout << "1) Move 2) Rest 3) View Stats 4) Quit: ";
std::cin >> selection;
Monster* monster = 0;
switch (selection)
{
case 1: // Move the player
gameMap.movePlayer();
if (gameMap.getPlayerXPos() == 2
&& gameMap.getPlayerYPos() == 3)
{
std::cout << "You see a store nearby !" << std::endl;
}
if (gameMap.getPlayerXPos() == 2
&& gameMap.getPlayerYPos() == 4)
{
Store store;
store.enter();
store.showInventory(mainPlayer);
}
//Check for a random encounter
//returns a null pointer if no encounter happened
monster = gameMap.checkRandomEncounter();
//'monster' not null, start battle script
if (monster != 0)
{
//Loop until a break statement
for (int i = 0; i < 3; i++)
{
//Display Hitpoints
mainPlayer.displayHitPoints();
monster[i].displayHitPoints();
std::cout << std::endl;
//Players turn to attack first
**bool runAway = mainPlayer.attack(monster, mainPlayer);** // Crash happening in this area
if (runAway) // Player flees
{
break;
}
if (monster[i].isDead())
{
mainPlayer.victory(monster->getXPReward(),
monster->getGoldReward());
mainPlayer.levelUp(mainPlayer);
}
break;
//Monster attacks
monster[i].attack(mainPlayer);
if (mainPlayer.isDead())
{
mainPlayer.gameOver();
done = true;
break;
}
}
//Pointer to Monster must destroy created instance of Monster
//to make sure that there is no Memory leak
}
delete monster;
monster = 0;
break;
case 2: // resting
mainPlayer.rest();
monster = gameMap.checkRandomEncounter();
//'monster' not null, start battle script
monster = gameMap.checkRandomEncounter();
//'monster' not null, start battle script
if (monster != 0)
{
//Loop until a break statement
for (int i = 0; i < 3; i++)
{
//Display Hitpoints
mainPlayer.displayHitPoints();
monster[i].displayHitPoints();
std::cout << std::endl;
//Players turn to attack first
bool runAway = mainPlayer.attack(monster, mainPlayer);
if (runAway) // Player flees
{
break;
}
if (monster[i].isDead())
{
mainPlayer.victory(monster->getXPReward(),
monster->getGoldReward());
mainPlayer.levelUp(mainPlayer);
}
break;
//Monster attacks
monster[i].attack(mainPlayer);
if (mainPlayer.isDead())
{
mainPlayer.gameOver();
done = true;
break;
}
}
//Pointer to Monster must destroy created instance of Monster
//to make sure that there is no Memory leak
}
delete monster;
monster = 0;
break;
case 3: // viewing stats
mainPlayer.viewStats();
break;
case 4: // quitting
done = true;
break;
}
}
return 0;
}
and finally the last puzzle piece, the function where the player attacks the Monster(s):
bool Player::attack(Monster Monster[], Player& Player)
{
int ArmorBefore = 0;
int Roll = 0;
int selection = 1;
int i;
if (Monster[0].isFilled() == true)
{
i = 0;
}
else if (Monster[1].isFilled() == true)
{
i = 1;
}
else if (Monster[2].isFilled() == true)
{
i = 2;
}
if (Monster[i].isFilled() == true)
{
std::cout << "1) Attack 2) Run 3) Cast Spell 4) Use Item: ";
std::cin >> selection;
std::cout << std::endl;
switch (selection)
{
case 1: // Player fights
std::cout << " You attack an " << Monster[i].getName()
<< " with a " << mWeapon.mName << std::endl;
if (Random(0, 20) < mAccuracy) // Player hits Monster
{
int damage = Random(mWeapon.mDamageRange);
int totalDamage = damage - Monster[i].getArmor();
if (totalDamage <= 0) // Armor is equal or higher than player atk
{
std::cout << "Your attack failed to penetrate "
<< Monster[i].getName() << "'s armor !"
<< std::endl;
return false;
}
else // Attack is higher than Monsters armor
{
std::cout << "You hit " << Monster[i].getName()
<< " for " << totalDamage << " damage !"
<< std::endl;
// Subtract dmg from Monsters hp
Monster[i].takeDamage(totalDamage);
return false;
}
}
else // Player Misses
{
std::cout << "You miss !" << std::endl;
}
std::cout << std::endl;
return false;
break;
case 2: // Player runs with a 25% chance
Roll = Random(1, 4);
if (Roll == 1) // Success
{
std::cout << "You run away !" << std::endl;
return true; // <- Return out of the function
}
else
{
std::cout << "You failed to escape !" << std::endl;
return false;
}
case 3: // Casting Spell
{
int SpellSelect;
// Spells for the Fighter
if (Player.mClassName == "Fighter")
{
std::cout << std::endl;
std::cout << "1) Shield 2) Mighty Blow: ";
std::cin >> SpellSelect;
if (SpellSelect == 1)
{
if (Player.mMagicPoints >= 10) // checks for player mana
{
std::cout << "You cast a mighty shield!"
<< std::endl;
ArmorBefore = Player.mArmor;
Player.shield(Player);
Player.mMagicPoints -= 10;
}
else
{
std::cout << "Not enough Mana" << std::endl;
break;
}
}
else
{
if (Player.mMagicPoints >= 5) // casting Mighty Blow
{
int damage = Random(mMightyBlow.mDamageRange);
std::cout
<< "You strike with all your might ! and Deal "
<< damage << " damage !" << std::endl;
Monster[i].takeDamage(damage);
Player.mMagicPoints -= 5;
return false;
}
else
{
std::cout << "Not enough Mana" << std::endl;
return false;
}
}
}
//Spells for the Wizard
else if (Player.mClassName == "Wizard")
{
std::cout << "1) Fireball";
std::cin >> SpellSelect;
if (Player.mMagicPoints >= 45)
{
int damage = Random(mFireball.mDamageRange);
std::cout << "You cast a Fireball and deal " << damage
<< " damage !" << std::endl;
Monster[i].takeDamage(damage);
Player.mMagicPoints -= 45;
return false;
}
else
{
std::cout << "Not enough Mana" << std::endl;
return false;
}
}
// Spells for the Cleric
else if (Player.mClassName == "Cleric")
{
std::cout << "1) Magic Missile";
std::cin >> SpellSelect;
if (Player.mMagicPoints >= 35)
{
int damage = Random(mMagicMissile.mDamageRange);
std::cout << "You cast a Magic Missile and deal "
<< damage << " damage !" << std::endl;
Monster[i].takeDamage(damage);
Player.mMagicPoints -= 35;
}
else
{
std::cout << "Not enough Mana" << std::endl;
return false;
}
}
}
case 4: // using Item
int invSlot;
std::cout << "1) HP Potion: ";
std::cin >> invSlot;
if (invSlot == 1) // Potion slot
{
if (mHPot.mAmount.size() > 0)
{
std::cout << "You used a Potion and healed for 5 HP !"
<< std::endl;
int currentSize = mHPot.mAmount.size();
mHPot.mAmount.resize(currentSize - 1);
Player.mHitPoints += 5;
if (Player.mHitPoints > Player.mMaxHitPoints)
{
Player.mHitPoints = Player.mMaxHitPoints;
}
return false;
}
else
{
std::cout << "You have no Potions!" << std::endl;
return false;
}
}
else // wrong slot
{
std::cout << "No Item found!" << std::endl;
return false;
}
}
// Clearing stat boosts
if (Player.shield(Player) == true)
{
Player.mArmor = ArmorBefore;
}
}
return false;
}
When I run the game, I sometimes have the problem, that after filling in a Monster in a slot of the array, no battle will be triggered. And if a battle will be triggered, I get a crash with an error report every time, which says:
_CrtlValidHeadPointer(block)
I guess that something with my pointer is not functioning well.... but since I am a beginner I am pretty much stuck. I would be very grateful for some enlightenment :)
This place can potentially call undefined behavior and crash:
int i;
if (Monster[0].isFilled() == true)
{
i = 0;
}
else if (Monster[1].isFilled() == true)
{
i = 1;
}
else if (Monster[2].isFilled() == true)
{
i = 2;
}
/*else // one of solutions
break;*/
//"i" can be unset! and can have any value from INT_MIN to INT_MAX!
if (Monster[i].isFilled() == true) //potentially index over array
{
Also there are memory leaks and undefined behavior with memory management:
Monster* monster = new Monster[3];
...
delete monster
must be delete [] monster
but it is recommended to use smart pointers, vector, array, etc, for memory management

how to make processes and they do different assign tasks for example doing reading from a file or writing to a file using fork

How to make processes and they do different assign tasks. I have written the code
#include<iostream>
using namespace std;
int main()
int status=0;
{
for(int i=0;i<5;i++)
{
if(fork()==0)
{ cout<<"do some thing"<<endl; }
else
{wait(status); }
}
return 0;
}
This code creates 5 processes but all will do same thing. I want them to do different tasks
The simplest thing to do is to check the value returned by the fork function, it will be equal to 0 in the child and to the process ID of the child in the parent process. You can use this fact to structure your code as follows:
if (fork() == 0) //Fork a child
{
//Put child 1 code here
return 0;
}
if (fork() == 0) //Fork a child
{
//Put child 2 code here
return 0;
}
if (fork() == 0) //Fork a child
{
//Put child 3 code here
return 0;
}
if (fork() == 0) //Fork a child
{
//Put child 4 code here
return 0;
}
if (fork() == 0) //Fork a child
{
//Put child 5 code here
return 0;
}
Notice that it doesn't make sense here to put it in a for loop because each child will have its own different code, but if you want to make the thing fit in a for loop then you should consider reading about the exec functions and placing the codes that you want in different programs.
Best of luck
use parameter 'i' .. the newly fork'd process can use case or if-then-else to invoke unique function per process.
Example:
uint32_t spinTillTime0SecChange(void)
{
uint32_t spin_count = 1; // time(0) invocation count
// no measurement, just spinning
time_t t0 = time(0);
time_t t1 = t0;
while (t0 == t1)
{
t1 = time(0);
spin_count += 1;
DTB::msPause(10); // uses usleep()
}
return(spin_count);
}
void child0(int i)
{
std::cout << "child0() start " << std::endl;
int k = 0;
time_t t0 = time(0) + 10; // spin for 10 seconds
do {
std::cout << "child0() " << i << "." << k++ << std::endl;
(void)spinTillTime0SecChange();
if (time(0) == t0) break;
}while(1);
exit(0); // do not return
}
void child1(int i)
{
std::cout << "child1() start " << std::endl;
int k = 0;
time_t t0 = time(0) + 10; // spin for 10 seconds
do {
std::cout << "child1() " << i << "." << k++ << std::endl;
(void)spinTillTime0SecChange();
if (time(0) == t0) break;
}while(1);
exit(0); // do not return
}
void child2(int i)
{
std::cout << "child2() start " << std::endl;
int k = 0;
time_t t0 = time(0) + 10; // spin for 10 seconds
do {
std::cout << "child2() " << i << "." << k++ << std::endl;
(void)spinTillTime0SecChange();
if (time(0) == t0) break;
}while(1);
exit(0); // do not return
}
void child3(int i)
{
std::cout << "child3() start " << std::endl;
int k = 0;
time_t t0 = time(0) + 10; // spin for 10 seconds
do {
std::cout << "child3() " << i << "." << k++ << std::endl;
(void)spinTillTime0SecChange();
if (time(0) == t0) break;
}while(1);
exit(0); // do not return
}
void child4(int i)
{
std::cout << "child4() start " << std::endl;
int k = 0;
time_t t0 = time(0) + 10; // spin for 10 seconds
do {
std::cout << "child4() " << i << "." << k++ << std::endl;
(void)spinTillTime0SecChange();
if (time(0) == t0) break;
}while(1);
exit(0); // do not return
}
int main(int /*argc*/, char** /*argv[]*/ )
{
uint32_t retVal = 0;
std::cout << std::endl;
for (int i = 0; i<5; ++i)
{
pid_t childPID = fork();
if(childPID == 0) // when 0 returned: child context
{
switch (i) // from loop, choose what this child will run
{
case 0: { child0(i); } break;
case 1: { child1(i); } break;
case 2: { child2(i); } break;
case 3: { child3(i); } break;
case 4: { child4(i); } break;
default:
{
std::cerr << "out of range i: " << i << std::endl;
DTB::msPause(10); // uses usleep
}
break;
} // switch (i)
}
dtbAssert(childPID >= 0)(childPID); // error check
}
// parent context
std::cout << "parent() context after fork" << std::endl;
int k = 0;
time_t t0 = time(0) + 13; // spin for 13 seconds
do {
std::cout << "parent() " << " " << " " << k++ << std::endl;
(void)spinTillTime0SecChange();
if (time(0) == t0) break;
}while(1);
return(retVal);
}

fread hanging, C++ with pipes

I'm writing a tictactoe application which communicates between a server and client file. Currently, my program hangs when trying to read in the players move. The client is showing successful write to the pipe but the server is not reading the information. Any help would be appreciated. Heres the offending code from both portions. Edit: I just realized the formatting got completely buggered in the copy/paste, I am sorry.
client main() :
//used to define int holder for server read in
const int MAX = 2;
//used to define buffers to transfer information
const int BUFFERS = 10;
//path of the global pipe
const string PRIMARY = "/home/mking/GPipe";
int main() {
//variables
size_t result;
srand(time(NULL) );
int s = rand() % 10000;
if (s < 1000) { s += 1000; }
cout << s << endl;
string userWrite = "/temp/" + to_string(s);
s = rand() % 10000;
if (s < 1000) { s += 1000; }
cout << s << endl;
string serverWrite = "/temp/" + to_string(s);
cout << PRIMARY << endl;
cout << "User pipe is " << userWrite << endl;
cout << "Server pipe is " << serverWrite << endl;
// send personal pipe information through global pipe to server
FILE * comms = fopen(PRIMARY.c_str(), "w");
cout << "Comms open" << endl;
result = fwrite(userWrite.c_str(), 1, userWrite.length(), comms);
if (result < userWrite.length()) { cout << endl << endl << endl << endl << endl << "write error, userfifo" << endl; }
result = fwrite(serverWrite.c_str(), 1, serverWrite.length(), comms);
if (result < userWrite.length()) { cout << endl << endl << endl << endl << endl << "write error, serverfifo" << endl; }
cout << "Comms written to" << endl;
//done with comms so close it
fclose(comms);
// for some reason sending /tmp/ caused a hang also, so i improvised
userWrite.erase(2,1);
serverWrite.erase(2,1);
// make the personal pipes
cout << userWrite << " " << serverWrite << endl;
mkfifo(userWrite.c_str(), 0777);
mkfifo(serverWrite.c_str(), 0777);
// open the personal pipes with read or write privelege
cout << "fifos made" << endl;
FILE * pwrite = fopen(userWrite.c_str(), "w");
cout << "pwrite open" << endl;
FILE * pread = fopen(serverWrite.c_str(), "r");
cout << "pread open" << endl;
// if either pipe did not get made correctly, print an error
if (pwrite == NULL ) { cout << "pwrite is wrong" << endl; }
if (pread == NULL ) { cout << "pread is wrong" << endl; }
// used to transfer information between pipes
string buffer = "/temp/0000";
string catcher = "/temp/0000";
// initialize curses functions
initscr();
noecho();
keypad(stdscr,TRUE);
cbreak();
WINDOW * screen = newwin(LINES/2, COLS/2, 0, 0);
wclear(screen);
keypad(screen,TRUE);
//wait for input before playing the game
int c = getch();
displayOpening(screen);
c = getch();
//initialize the game data types
int row = 0;
int column = 0;
vector<pair<int, int> > userMoves;
vector<pair<int,int> > serverMoves;
int charInt[MAX];
bool invalid = 0;
//until game is over or user exits
while (1) {
// update the board
displayBoard(screen,userMoves,serverMoves, row, column, invalid);
// based on user input, do stuff, supports wsad or arrow keys
switch(c = getch() ) {
// if go up, move up a row or go back to bottom if at top
case KEY_UP:
case 'w':
if (row == 0) { row = 2; }
else { row--; }
break;
// if go down, move down a row or go back to the top if at bottom
case KEY_DOWN:
case 's':
if (row == 2) { row = 0; }
else { row++; }
break;
// if go left, move left a column or go back to the far right if at far left
case KEY_LEFT:
case 'a':
if (column == 0) { column = 2; }
else { column--; }
break;
// if go right, move right a column or go back to the far left if at far right
case KEY_RIGHT:
case 'd':
if (column == 2) { column = 0; }
else { column++; }
break;
// if spacebar is pressed, enter move if valid, otherwise tell invalid and get more input
case ' ':
if (checkX(row, column, userMoves, serverMoves)) {
invalid = 0;
// no longer used function, thought maybe was the issue
//addX(row,column,userMoves,buffer);
//catch information in buffer to send to server
buffer[8] = (row + '0');
buffer[9] = (column + '0');
//cout << "buffer 0 and 1 are " << int(buffer[0]) << " " << int(buffer[1]) << endl;
// add newest move to the list of user moves
userMoves.push_back(make_pair(row,column));
// check if the game is over, send a game over message to server if so and exit/clean up pipes
if (checkValid(userMoves,serverMoves) == 0 || (userMoves.size() + serverMoves.size() == 9) ) {
youwin(screen);
buffer[8] = (3 + '0');
buffer[9] = (3 + '0');
result = fwrite(buffer.c_str(), 1, buffer.length(), pwrite);
if (result < BUFFERS) { cout << endl << endl << endl << endl << endl << "write error, usermove" << endl; }
fclose(pread);
fclose(pwrite);
unlink(userWrite.c_str());
unlink(serverWrite.c_str());
endwin();
return 0;
}
//mvwaddch(screen, 12, 1, 'k');
//wrefresh(screen);
//cout << endl << endl << endl << endl << endl << buffer << " " << buffer.length() << endl;
// write newest move to server, currently where hangs!!!!!!
result = fwrite(buffer.c_str(),1,buffer.length(),pwrite);
if (result < BUFFERS) { cout << endl << endl << endl << endl << endl << "write error, usermove" << endl; }
//cout << endl << "written successfully" << endl;
//mvwaddch(screen,12,1,'l');
//wrefresh(screen);
// read in server counter move
result = fread(&catcher[0],1,BUFFERS,pread);
if (result < BUFFERS) { cout << endl << endl << endl << endl << endl << "read error, servermove" << endl; }
// catch newest computer move
charInt[0] = (catcher[8] - '0');
charInt[1] = (catcher[9] - '0');
// if the server says it won, clean up pipes and exit
if (charInt[0] == 3 && charInt[1] == 3) {
youlose(screen);
fclose(pread);
fclose(pwrite);
unlink(userWrite.c_str());
unlink(serverWrite.c_str());
endwin();
return 0;
}
// check if the server made a valid move
if (checkX(charInt[0], charInt[1], userMoves, serverMoves)) { invalid = 1; }
//addX(charInt[0],charInt[1],serverMoves,catcher);
// add newest server move to list of server moves
serverMoves.push_back(make_pair(charInt[0],charInt[1]));
// if server has won or a draw, tell the server and clean up pipes/exit
if (checkValid(userMoves,serverMoves) == 0) {
youlose(screen);
buffer[8] = (3 + '0');
buffer[9] = (3 + '0');
result = fwrite(&buffer[0],1,BUFFERS,pwrite);
if (result < BUFFERS) { cout << endl << endl << endl << endl << endl << "write error, usermove" << endl; }
fclose(pread);
fclose(pwrite);
unlink(userWrite.c_str());
unlink(serverWrite.c_str());
endwin();
return 0;
}
}
// if the move was invalid say so
else { invalid = 1; }
break;
// if user wants to exit, tell the server and clean up/exit
case 'q':
buffer[8] = 3 + '0';
buffer[9] = 3 + '0';
result = fwrite(&buffer[0],sizeof(char),BUFFERS,pwrite);
if (result < BUFFERS) { cout << endl << endl << endl << endl << endl << "write error, usermove" << endl; }
fclose(pread);
fclose(pwrite);
unlink(userWrite.c_str());
unlink(serverWrite.c_str());
endwin();
return 0;
break;
default:
break;
}
}
return 0;
}
server main() :
const int GRID = 9;
const int MAX_G = 10;
const int MAX_L = 10;
const string PRIMARY="/home/mking/GPipe";
int main() {
// variables to hold personal pipe input
char userWrite[MAX_L];
char serverWrite[MAX_L];
// open global pipe and prepare for input
cout << PRIMARY << endl;
FILE * comms = fopen(PRIMARY.c_str(), "r");
cout << "comms open" << endl;
pid_t pid;
bool valid = 1;
int charInt[MAX_G];
char prev[] = "/temp/0000";
size_t result;
// run until forced to close
while(1) {
// get the personal pipe names
//cout << "about to read user" << endl;
result = fread(&userWrite[0], sizeof(char),MAX_L,comms);
if (result < MAX_L && result > 0) { cout << "read error, user" << endl; }
//cout << "read user" << endl;
result = fread(&serverWrite[0], sizeof(char), MAX_L,comms);
if (result < MAX_L && result > 0) { cout << "read error, server" << endl; }
//cout << "read server" << endl;
//cout << "User pipe is " << userWrite << endl;
//cout << "Server pipe is " << serverWrite << endl;
// if a new pipe was detected, fork and play against a client
if (strcmp(prev, userWrite) != 0) { pid = fork(); }
strcpy(prev, userWrite);
// if a chiled, play against a client
if (pid == 0) {
//close comms and open personal pipes
cout << "In child" << endl;
fclose(comms);
string user(userWrite);
string server(serverWrite);
// was having issues with fread earlier also, roundabout fix
user.erase(2,1);
server.erase(2,1);
// set up pipes
cout << "opened pipes " << user << " " << server << endl;
FILE * userFifo = fopen(user.c_str(), "r");
cout << "opened user pipe" << endl;
FILE * serverFifo = fopen(server.c_str(), "w");
cout << "opened server pipe" << endl;
// set up data for server to check moves
pair<int,int> move;
vector<pair<int,int> > userMoves;
vector<pair<int,int> > serverMoves;
char buffer[MAX_G] = {'/','t','e','m','p','/','0','0' };
char filler[MAX_G];
vector<bool> untaken (GRID, 1);
// while game not over
while (valid) {
// get a new move, HANGS HERE!!!!!
cout << "waiting for user move" << endl;
result = fread(&filler[0], sizeof(char), MAX_G, userFifo);
if (result < MAX_G) { cout << "read error, usermove" << endl; }
cout << "move read in" << endl;
// catch user move
charInt[0] = filler[6] - '0';
charInt[1] = filler[7] - '0';
cout << charInt[0] << " " << charInt[1] << endl;
// if user says game over, close pipes
if (charInt[0] == 3 && charInt[1] == 3) {
fclose(userFifo);
fclose(serverFifo);
exit(0);
}
// add user move to list of moves
userMoves.push_back(make_pair(charInt[0], charInt[1]));
// mark location of taken moves
untaken[(userMoves.back().first * 3 + userMoves.back().second)] = 0;
// see if game can be ended and add a server move
valid = checkX(userMoves,serverMoves, untaken);
untaken[(serverMoves.back().first * 3 + serverMoves.back().second)] = 0;
//prepare server move for writing
buffer[6] = serverMoves.back().first + '0';
buffer[7] = serverMoves.back().second + '0';
//buffer[0] = -1;
//buffer[1] = -1;
// write servermove to client
//cout << buffer[0] << " " << buffer[1] << endl;
result = fwrite(&buffer[0],sizeof(char),MAX_G,serverFifo);
if (result < MAX_G) { cout << "write error, servermove" << endl; }
}
// close pipes if game is over
fclose(userFifo);
fclose(serverFifo);
exit(0);
}
}
fclose(comms);
return 0;
}

Simple External hack for Assault Cube gone wrong?

So I'm following a Youtube tutorial on making a simple external hack for Assault Cube.
I reach part 6 of the tutorial and... blam. My compiler is giving me the error:
[Error] expected declaration before '}' token
So I add that. And it just repeats.
I'm using Orwells Dev C++ and have NO idea where I've gone wrong.
Harsh criticism welcome, including those "you're jumping too ahead of yourself. Try something more simple." etc etc
// Youtube Console Trainer Tutorial -- Trainer for Assault Cube
#include <iostream>
#include <windows.h>
#include <string>
#include <ctime>
std::string GameName = "AssaultCube";
LPCSTR LGameWindow = "AssaultCube";
std::string GameStatus;
bool IsGameAvail;
bool UpdateOnNextRun;
//Ammo Variables
bool AmmoStatus;
BYTE AmmoValue[] = {0xA3, 0X1C, 0X0, 0X0};
DWORD AmmoBaseAddress = {0x004DF73C};
DWORD AmmoOffsets[] = {0x378, 0x14, 0x0};
//Health Variables
bool HealthStatus;
BYTE HealthValue[] = {0x39, 0X5, 0X0, 0X0};
DWORD HealthBaseAddress = {0x004DF73C};
DWORD HealthOffsets[] = {0xF4};
int main()
{
HWND hGameWindow = NULL;
int timeSinceLastUpdate = clock();
int GameAvailTMR = clock();
int onePressTMR = clock();
DWORD dwProcID = NULL;
HANDLE hProcHandle = NULL;
UpdateOnNextRun = true;
std::string sAmmoStatus = "OFF";
std::string sHealthStatus = "OFF";
while(!GetAsyncKeyState(VK_INSERT))
{
if(clock() - GameAvailTMR > 100)
{
GameAvailTMR = clock();
IsGameAvail = false;
hGameWindow = FindWindow(NULL,LGameWindow);
if (hGameWindow)
{
GetWindowThreadProcessId( hGameWindow, &dwProcID);
if(dwProcID != 0);
{
hProcHandle =
OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcID);
if(hProcHandle == INVALID_HANDLE_VALUE || hProcHandle == NULL )
{
GameStatus = "Failed to open process for valid handle";
}
else{
GameStatus = "AssaultCube Ready To Hack";
IsGameAvail = true;
}
else{
GameStatus = "Failed to get process ID";
}
else {
GameStatus = "AssaultCube NOT FOUND";
}
if(UpdateOnNextRun || clock() - timeSinceLastUpdate > 5000 )
system("cls");
std::cout << "-------------------------------------"<< std::endl;
std::cout << " AssaultCube memory hacker" << std::endl;std::endl;
std::cout << "-------------------------------------"<< std::endl;
std::cout << "GAME STATUS:" << GameStatus << std::endl << std::endl;
std::cout << "[F1] Unlimited Ammo -> " << sAmmoStatus << " <- " << std::endl << std::endl;
std::cout << "[F2] Unlimited Health -> " << sHealthStatus << " <- " << std::endl << std::endl;
}
}
}
}
}
}
}
A missing { here:
if(UpdateOnNextRun || clock() - timeSinceLastUpdate > 5000 )
And after the line with GameStatus = "AssaultCube Ready To Hack"; there are two other else without if. Remove/comment them.
And next time, better indentation!
The problem is that your else clauses are nested, when they should be outside their respective if clauses. Let's shuffle some braces around:
hGameWindow = FindWindow(NULL,LGameWindow);
if (hGameWindow)
{
GetWindowThreadProcessId( hGameWindow, &dwProcID);
if(dwProcID != 0);
{
hProcHandle =
OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcID);
if(hProcHandle == INVALID_HANDLE_VALUE || hProcHandle == NULL )
{
GameStatus = "Failed to open process for valid handle";
}
else{
GameStatus = "AssaultCube Ready To Hack";
IsGameAvail = true;
}
}
else{
GameStatus = "Failed to get process ID";
}
}
else {
GameStatus = "AssaultCube NOT FOUND";
}
if(UpdateOnNextRun || clock() - timeSinceLastUpdate > 5000 )
{
system("cls");
std::cout << "-------------------------------------"<< std::endl;
std::cout << " AssaultCube memory hacker" << std::endl;std::endl;
std::cout << "-------------------------------------"<< std::endl;
std::cout << "GAME STATUS:" << GameStatus << std::endl << std::endl;
std::cout << "[F1] Unlimited Ammo -> " << sAmmoStatus << " <- " << std::endl << std::endl;
std::cout << "[F2] Unlimited Health -> " << sHealthStatus << " <- " << std::endl << std::endl;
}
GetWindowThreadProcessId( hGameWindow, &dwProcID);
if(dwProcID != 0);
{
it should be:
GetWindowThreadProcessId( hGameWindow, &dwProcId);
if(dwProcID != 0);
{
it's a little d. in dwProcID