Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #include <fcntl.h>
- #include <sys/stat.h>
- #include <unistd.h>
- #include <pthread.h>
- #include <iostream>
- #include <cstdlib>
- using namespace std;
- string username;
- int stop=0;
- void* reader(void* directory){
- char* myfifo = (char*) directory;
- mkfifo(myfifo,0606);
- char readArr[256];
- int ReadFD, delay;
- while(1){
- if(delay>0){
- usleep(10000);
- delay=0;
- }
- ReadFD = open(myfifo,O_RDONLY);
- read(ReadFD,readArr,sizeof(readArr));
- string text = readArr;
- cout<<text<<endl;
- if(text.substr(0,username.length()) == username){
- int WriteFd = open(myfifo, O_WRONLY);
- write(WriteFd,readArr,sizeof(readArr)+1);
- close(WriteFd);
- delay++;
- }else{
- }
- close(ReadFD);
- }
- pthread_exit(NULL);
- }
- void* write(void* directory){
- char* myfifo = (char*) directory;
- mkfifo(myfifo,0666);
- const char* writeArr;
- int WriteFd;
- string input;
- while(1){
- usleep(1000);
- cout<<"Enter your message (enter <tab> for help):\n";
- getline(cin, input);
- if(input=="\t"){
- cout<<"Special keywords: 'exit' to close, 'clear' to clear chat screen\n";
- }else if(input=="exit"){
- cout<<"You have left the chatroom.\n";
- stop++;
- }else if(input=="clear"){
- system("clear");
- }else{
- WriteFd = open(myfifo,O_WRONLY);
- string fulltext = username+": "+input;
- writeArr=fulltext.c_str();
- write(WriteFd,writeArr,strlen(writeArr)+1);
- close(WriteFd);
- }
- }
- pthread_exit(NULL);
- }
- int main(){
- system("clear");
- cout<<"Please enter your name: ";
- getline(cin, username);
- system("clear");
- cout<<"Hello "<<username<<"\nWelcome to our chat room\n";
- pthread_t treader, twriter;
- const char* myfifo= "/tmp/my/fifo";
- int rc=pthread_create(&treader,NULL,reader,(void*) myfifo);
- if(rc){
- cout<<"Unable to create thread "<<rc<<endl;
- exit(-1);
- }
- rc=pthread_create(&twriter,NULL,writer,(void*) myfifo);
- if(rc){
- cout<<"Unable to create thread "<<rc<<endl;
- exit(-1);
- }
- while(stop==0){
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement