-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathq1_client.c
90 lines (73 loc) · 2.39 KB
/
q1_client.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
void action();
struct Data { //struct for the communication of server and client
int letters_left;
char word[100];
int attempts_left;
int pid;
char letter;
};
struct mesg_buffer { //struct used in message queues
long mesg_type;
char d[1024];
} message;
int main()
{
signal(SIGUSR1, action); //associated action method with the signal
key_t key;
int msgid;
int my_pid=getpid(); //getting process id of this process
key = ftok("file", 65);
msgid = msgget(key, 0666 | IPC_CREAT); //created message queue
message.mesg_type=1;
strcpy(message.d,"hi");
msgsnd(msgid, &message, sizeof(message), 0); //sending hi to server
msgrcv(msgid, &message, sizeof(message), 1, 0); //receiving shared memory key from the server
printf("Data Received is : %s \n", message.d);
int x_key=atoi(message.d);
int key_=shmget(x_key,1024,0); //accessing shared memory
struct Data* data=(struct Data *) shmat(key_,NULL,0);
printf("Letters Left: %d\n",data->letters_left);
printf("Attempts Left: %d\n",data->attempts_left);
printf("Word is: %s\n", data->word);
int server_pid=data->pid;
printf("Enter your guess: ");
scanf("%c",&(data->letter)); //getting guess from the user
getchar(); //just to ignore \n character
data->pid=my_pid;
kill( server_pid, SIGUSR1 ); //sending signal to server
while(1==1)
{
pause(); //waiting for signal from the server
if(data->attempts_left == 0) //if user loses then exit loop
{
break;
}
if(data->letters_left == 0) //if user wins then print congrats and exit loop
{
printf("You win! :D Congratulations!!!\n");
break;
}
printf("Letters Left: %d\n",data->letters_left);
printf("Attempts Left: %d\n",data->attempts_left);
printf("Word is: %s\n", data->word);
printf("Enter your guess: ");
scanf("%c",&(data->letter)); //getting guess from the user
getchar();
kill( server_pid, SIGUSR1 ); //signaling server that user has entered the guess and updated the shared memory
}
shmdt(data);
shmctl(key_,IPC_RMID,NULL);
return 0;
}
void action() //just a function for signal
{
return;
}