String Validation in a Certain Format - c++

I'm creating a simple chess game which uses shared memory. There are two players (Black,White) in the game and they are working in Strict Alternation principle. I get input from every player in turn-based sense and use them. My question is: I want the user to give the input like mov(a1,b2). After getting the input First: I want to validate if it is in the correct format and then I want to use the a1,b2 values in a function. Here is the part of my code:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <stdlib.h>
#include <iostream>
using namespace std;
#define SHMSZ 27
int main() {
int shmid;
key_t key;
char *shm;
string cmd;
int check =1;
key = 111;
/*
* Locate the segment.
*/
if ((shmid = shmget(key, SHMSZ, 0666)) < 0) {
perror("shmget");
return 0;
}
/*
* Now we attach the segment to our data space.
*/
if ((shm = (char*) shmat(shmid, NULL, 0)) == (char *) -1) {
perror("shmat");
return 0;
}
cout << *shm << endl;
while(check)
{
if(*shm == '*') //checks if other player finished the game
{
cout<<"End of the game. Thank you for playing." <<endl;
*shm ='*';
exit(1);
}
while(*shm == 'B')
{
cout << "Enter a move" << endl;
cin >> cmd;
if(cmd=="eog") // Finish the game
{
cout<<"End of the game. Thank you for playing." <<endl;
*shm ='*';
exit(1);
}
*shm = 'W';
}
}
return 0;
}

Related

how to reboot the application when there is a change in last modification time of an accesed file in that application

I'm new to thread programming. I'm trying to create an application which continually checks the Last Modification time of some file and exits the program when that time has changed.
Please find my code below:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <cerrno>
#include <unistd.h>
using namespace std;
#define NUM_THREADS 2
void *getFileCreationTime(void *path) {
const char *pt;
pt=(const char *)path;
struct stat attr;
stat("/home/utthunga/shmrp.cpp", &attr);
while(1){
char *timestamp= ctime(&attr.st_mtime);
if(timestamp)
{
cout<<"Last modified time: %s"<< ctime(&attr.st_mtime)<<endl;
cout<<"No changes has been made to the file"<<endl;
sleep(4);
}
else
{
cout<<"Last modified time: %s"<< ctime(&attr.st_mtime)<<endl;
cout<<"Time stamp has been changed"<<endl;
exit(0);
}
}
pthread_exit(NULL);
}
int main()
{
pthread_t threads[NUM_THREADS];
int i;
int rc;
for( i = 0; i < NUM_THREADS-1; i++ )
rc = pthread_create(&threads[i], NULL, getFileCreationTime, (void *)i);
pthread_exit(NULL);
return 0;
}
Can anyone please tell me what changes I have to implement in order to check the last modification time of that file continually and exit the application when that time has changed?
After you retrieve the file's modification time the first time, you need to save it so you can compare it to subsequent values retrieved afterwards.
Try something more like this instead:
void* getFileCreationTime(void *) {
const char *path = "/home/utthunga/shmrp.cpp";
struct stat attr;
if (stat(path, &attr) < 0) {
cout << "stat error" << endl;
exit(0);
}
time_t mtime = attr.st_mtime;
cout << "Last modified time: " << ctime(&mtime) << endl;
while(1) {
sleep(4);
if (stat(path, &attr) < 0) {
cout << "stat error" << endl;
exit(0);
}
if (attr.st_mtime != mtime) {
cout << "Time stamp has been changed" << endl;
exit(0);
} else {
cout << "No changes have been made to the file" << endl;
}
}
pthread_exit(NULL);
}

Having issues with mmap from within a function

I'm trying to write a function that has mmap within it, however when I try to access the memory from main(), it gets a segfault. Does anyone have any idea why?
Please ignore the MPI headers - it's for the later part of the project. I have commented out the mprotect line to see that it is an mmap fault as opposed to the handler not necessarily working
net_map.cpp:
#include <iostream>
#include <signal.h>
#include <sys/mman.h>
#include <mpi.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "net_map.h"
using namespace std;
void handler(int sig, siginfo_t* info, void* other)
{
void* address = info->si_addr;
cout << "\nSegfault Detected! [Address: " << address << "]\n" << endl;
int unprotectresult = mprotect(address, SIZE, PROT_READ|PROT_WRITE|PROT_EXEC);
if (unprotectresult == 0)
{
cout << "\nSuccessful mprotect (memory unprotected)!\n" << endl;
}else
{
cout << "\nMprotect unsuccessful\n" << endl;
}
}
void netmap (char filename[], char* mapped)
{
int file;
file = open(filename, O_RDWR);
mapped = (char*) mmap(NULL, SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, file, 0);
if (mapped == MAP_FAILED)
{
cout << "\nMap Failed!" << endl;
}
cout << mapped << endl;
}
main.cpp
#include <iostream>
#include <signal.h>
#include <sys/mman.h>
#include <mpi.h>
#include <unistd.h>
#include <array>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <array>
#include "net_map.h"
using namespace std;
int main(int argc, char* argv[])
{
struct sigaction segaction;
memset(&segaction, 0, sizeof(segaction));
segaction.sa_flags = SA_SIGINFO;
sigemptyset(&segaction.sa_mask);
segaction.sa_sigaction = handler;
sigaction(SIGSEGV, &segaction, NULL);
int i;
char* mapped;
networkpage sheet;
char filename[] = "hello.txt";
netmap(filename, mapped);
sheet.address = (void*)mapped;
cout << "\nAddress: " << sheet.address << endl;
//mprotect(sheet.address, SIZE, PROT_NONE);
memcpy(sheet.address, "k", 1);
munmap(sheet.address, SIZE);
return 0;
}

Using multithreading to get continuous beep sound

I'm trying to create a program in C++ where I play a beep sound, with a frequency and duration of the user's choice.
The program needs to continue running while playing the beep sound.
I figured out I should use multi-threading for this, but I don't have any experience with this.
For example, this is a simple program, but I get an error when I use _beginthread:
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <process.h>
using namespace std;
int freq = 0;
int sec = 0;
int mil = 0;
void beepTone(int freqq, int mill)
{
Beep(freqq, mill);
_endthread();
}
int main()
{
cout << "Frequency?" << endl;
cin >> freq;
cout << "Duration?" << endl;
cin >> sec;
mil = 1000 * sec;
_beginthread(beepTone(freq, mil), 0, NULL);
cout << "Test Threading";
return 0;
}
Argument of type "void(*)(int freqq, int mill)" is incompatible with parameter of type "_beginthread_proc_type"
I think the point of this testing program is pretty clear.
I have code that runs, but in this code I can't choose my own frequency and duration:
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <process.h>
using namespace std;
void beepTone(void *arg)
{
Beep(1000, 3000);
_endthread();
}
int main()
{
_beginthread(beepTone, 0, NULL);
cout << "Test Threading";
cin.get();
return 0;
}
This one plays 1000Hz for 3 sec while continuing the program.
Can anyone help me on how can I tell the thread which frequency and duration to play?
Your first example fails to compile because you are actually calling beepTone() and then trying to pass its void return value to the start_address parameter of _beginthread(), which will not work. You need to pass beepTone() itself to that parameter, not its return value.
Your second example is correctly passing beepTone() itself to _beginThread(), but is not passing any data to beepTone().
Now, to accomplish what you want, _beginthread() has an arglist parameter that you can use to pass user data to your thread function. That is what you need to use to send your beep values to the thread so it can then pass them to Beep().
Try something like this:
#include "stdafx.h"
#include <Windows.h>
#include <process.h>
#include <iostream>
using namespace std;
struct beepParams
{
int freq;
int mil;
};
void __cdecl beepTone(void *arg)
{
beepParams *params = static_cast<beepParams*>(arg);
Beep(params->freq, params->mil);
delete params;
_endthread();
}
int main()
{
int freq = 0, sec = 0, mil = 0;
cout << "Frequency?" << endl;
cin >> freq;
cout << "Duration?" << endl;
cin >> sec;
mil = 1000 * sec;
beepParams *params = new beepParams;
params->freq = freq;
params->mil = mil;
if (_beginthread(&beepTone, 0, params) == -1)
delete params;
cout << "Test Threading";
//...
cin.get();
return 0;
}
That being said, if you are using C++11 or later, consider using std::thread instead:
#include "stdafx.h"
#include <Windows.h>
#include <iostream>
#include <thread>
using namespace std;
struct beepParams
{
int freq;
int mil;
};
void beepTone(beepParams params)
{
Beep(params.freq, params.mil);
}
int main()
{
int freq = 0, sec = 0, mil = 0;
cout << "Frequency?" << endl;
cin >> freq;
cout << "Duration?" << endl;
cin >> sec;
mil = 1000 * sec;
beepParams params;
params.freq = freq;
params.mil = mil;
thread t(beepTone, params);
t.detach();
cout << "Test Threading";
//...
cin.get();
return 0;
}

Program1 Accepts Input From User, Then Program2 Prints Out To Screen

I have a server and a client program. Server program prompts user to enter text, then sends user input to client. The client prints out user text to screen. So far server program prompts user to enter text and when I run client program it displays nothing. Any recommendations to make programs work. Below are both programs.
// server.cpp
// g++ -o server server.cpp -lpthread -lrt
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <semaphore.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string>
#include <ctype.h>
#include <iostream>
using namespace std;
string UserInput(string);
#define SHMSZ 27
char SEM_NAME[]= "vik";
int main(void)
{
char ch;
int shmid;
key_t key;
char *shm,*s;
sem_t *mutex;
string input;
//name the shared memory segment
key = 1000;
//create & initialize semaphore
mutex = sem_open(SEM_NAME,O_CREAT,0644,1);
if(mutex == SEM_FAILED)
{
perror("unable to create semaphore");
sem_unlink(SEM_NAME);
exit(-1);
}
//create the shared memory segment with this key
shmid = shmget(key,SHMSZ,IPC_CREAT|0666);
if(shmid<0)
{
perror("failure in shmget");
exit(-1);
}
//attach this segment to virtual memory
shm = (char*) shmat(shmid,NULL,0);
//start writing into memory
s = shm;
// Enter user input
//cout << "Enter your input: ";
//cin >> input;
// Display user input
//cout << "You entered: "<< input << endl;
//return 0;
while(1)
{
cout << "Enter your input: ";
cin >> input;
sem_wait(mutex);
//*s++ = count;
sem_post(mutex);
//return 0;
}
//the below loop could be replaced by binary semaphore
while(*shm != '*')
{
sleep(1);
}
sem_close(mutex);
sem_unlink(SEM_NAME);
shmctl(shmid, IPC_RMID, 0);
_exit(0);
}
-
// client.cpp
// g++ -o client client.cpp -lpthread -lrt
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <semaphore.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <ctype.h>
using namespace std;
string UserInput(string);
#define SHMSZ 27
char SEM_NAME[]= "vik";
int main(void)
{
char ch;
int shmid;
key_t key;
char *shm,*s;
sem_t *mutex;
string input;
//name the shared memory segment
key = 1000;
//create & initialize existing semaphore
mutex = sem_open(SEM_NAME,0,0644,0);
if(mutex == SEM_FAILED)
{
perror("reader:unable to execute semaphore");
sem_close(mutex);
exit(-1);
}
//create the shared memory segment with this key
shmid = shmget(key,SHMSZ,0666);
if(shmid<0)
{
perror("reader:failure in shmget");
exit(-1);
}
//attach this segment to virtual memory
shm = (char*) shmat(shmid,NULL,0);
//start reading
s = shm;
while(1)
{
cout << "You entered: " << input << endl;
//cin >> input;
sem_wait(mutex);
putchar(*s);
sem_post(mutex);
return 0;
}
//once done signal exiting of reader:This can be replaced by another semaphore
*shm = '*';
sem_close(mutex);
shmctl(shmid, IPC_RMID, 0);
exit(0);
}

C++ Program Compiles in Windows and Linux. But Doesn't Work on Linux

I think it might be something related to the way my pointers are used/initialized in my struct, but I'm not completely sure. I use 'g++ -lpthread main.cpp' to compile. The program just hangs in Linux, while executing properly in windows. The program doesn't even spit out a cout I put in the beginning of the code for debugging purposes.
#include "pthread.h"
#include "semaphore.h"
#include "time_functions.h"
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
struct vars {
char buffer[10][1000];
int put;
int take;
sem_t openSlot;
sem_t slotInactive;
sem_t newData;
ifstream readFile;
ofstream writeFile;
};
void *write(void *in) //consumer, writes data to file and deletes data from buffer
{
vars* writeVars = (vars*)in;
while (true)
{
sem_wait(&(*writeVars).newData);
sem_wait(&(*writeVars).slotInactive);
if ((*writeVars).buffer[(*writeVars).take % 10][0] != '$')
{
(*writeVars).writeFile << (*writeVars).buffer[(*writeVars).take % 10];
if ((*writeVars).readFile.eof() != true)
{
(*writeVars).writeFile << endl;
}
else
{
break;
}
}
(*writeVars).take++;
sem_post(&(*writeVars).openSlot);
sem_post(&(*writeVars).slotInactive);
}
pthread_exit(0);
return 0;
}
void *read(void *in) //producer, reads data into buffer
{
vars* readVars = (vars*)in;
char read_line[1000];
while ((*readVars).readFile.getline(read_line, 1000))
{
sem_wait(&(*readVars).openSlot);
sem_wait(&(*readVars).slotInactive);
strcpy((*readVars).buffer[(*readVars).put % 10], read_line);
(*readVars).put++;
sem_post(&(*readVars).slotInactive);
sem_post(&(*readVars).newData);
}
sem_wait(&(*readVars).openSlot);
sem_wait(&(*readVars).slotInactive);
(*readVars).buffer[(*readVars).put % 10][0] = '$';
sem_post(&(*readVars).slotInactive);
sem_post(&(*readVars).newData);
pthread_exit(0);
return 0;
}
int main(int argc, char* argv[])
{
char pause[10];
vars *varsPointer, var;
varsPointer = &var;
var.take = 0;
var.put = 0;
var.writeFile.open(argv[2], ios::out);
var.readFile.open(argv[1], ios::in);
start_timing();
sem_init(&var.openSlot, 0, 10);
sem_init(&var.slotInactive, 0, 1);
sem_init(&var.newData, 0, 0);
pthread_t read_Thread, write_Thread;
pthread_create(&read_Thread, NULL, read, varsPointer);
pthread_create(&write_Thread, NULL, write, varsPointer);
pthread_join(read_Thread, NULL);
pthread_join(write_Thread, NULL);
sem_destroy(&var.openSlot);
sem_destroy(&var.slotInactive);
sem_destroy(&var.newData);
stop_timing();
var.readFile.close();
var.writeFile.close();
//Display timer
cout << "wall clock time (ms):" << get_wall_clock_diff() * 1000 << '\n';
cout << "cpu time (ms):" << get_CPU_time_diff() * 1000 << '\n';
cout << "Type Something and Press Enter To Continue";
cin >> pause; //Just used to keep cmd promt open in Windows after program execution
return 0;
}