kill() function problem in client-server ipc message using 2 FIFOs - c

I want to have a message send & receive through 2 uni-direction FIFO
Flow of data
FIFO1
stdin--->parent(client) writefd--->FIFO1-->child(server) readfd
FIFO2
child(server) writefd2---->FIFO2--->parent(client) readfd2--->stdout
I need to have boundary structed message mesg_len+mesg_type+mesg_data
The function is that if user input "Knock Knock" on stdin, which directs to client, client send this message to server through FIFO1, server compares the string, if matches with "Knock Knock", then server reply message "Who's there?" to client through FIFO2, and client write this message to the stdout.
The interactive part is like:
client:Knock Knock
server:who's there
client:eric
server:eric,welcome
client:exit
all signal terminate
Below is my code:
I need help on kill() signals when client types "exit".It seems the client process still live after call kill(). So i need to type ctrl+c to end
Please help me. Thanks a lot!
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#define MAX_BUF 100
#define MAXMESGDATA (MAX_BUF - 2* sizeof(long))
#define MESGHDRSIZE (sizeof(struct mymesg)-MAXMESGDATA)
#define FIFO1 "/tmp/fifo.1"
#define FIFO2 "/tmp/fifo.2"
#define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
struct mymesg{
long mesg_len; //byte in mesg_data
long mesg_type; //message type
char mesg_data[MAXMESGDATA];
};
ssize_t mesg_send (int fd, struct mymesg *mptr){
return (write (fd,mptr,MESGHDRSIZE + mptr->mesg_len));
}
ssize_t mesg_recv(int fd,struct mymesg *mptr){
size_t len;
ssize_t n;
if ((n=read(fd,mptr,MESGHDRSIZE))==0) {//read hear first, get len of data
return 0; //end of file
} else if (n!=MESGHDRSIZE){
printf("message header: expected %d, got %d\n", MESGHDRSIZE,n);
exit(1);
}
if ((len=mptr->mesg_len)>0)
{
if ((n=read(fd,mptr->mesg_data,len))!=len)
{
printf("message data: expected %d, got %d\n", len,n);
exit(1);
}
}
return len;
}
void client(int readfd,int writefd){
size_t len;
ssize_t n;
struct mymesg mesg;
for (;;)
{
printf("\nClient:");
fgets(mesg.mesg_data,MAXMESGDATA,stdin);//read mesg
len=strlen(mesg.mesg_data);
if (mesg.mesg_data[len-1]=='\n') //ignore newline
len--;
mesg.mesg_len=len;
mesg.mesg_type=1;
mesg_send(writefd,&mesg);//write to IPC channel
//read from IPC,write to std output
if((n=mesg_recv(readfd,&mesg))>0)
write(STDOUT_FILENO,mesg.mesg_data,n);
}
}
void server(int readfd,int writefd){
ssize_t n;
struct mymesg mesg;
for(;;)
{
mesg.mesg_type=1;
//read from IPC channel
if ((n=mesg_recv(readfd,&mesg))==0){
printf("Message missing");
exit(1);
}
mesg.mesg_data[n]='\0';
mesg.mesg_len=strlen(mesg.mesg_data);
char* str=NULL;
if (strcasecmp ("Knock Knock", mesg.mesg_data)==0){
str="Server:Who's there?";
strcpy(mesg.mesg_data,str);
mesg.mesg_len=strlen(str)-1;
}
else if(strcasecmp ("Eric", mesg.mesg_data)==0){
str="Server:Eric,Welcome!";
strcpy(mesg.mesg_data,str);
mesg.mesg_len=strlen(str)-1;
}
else if(strcasecmp ("Exit", mesg.mesg_data)==0){
kill(getpid(),SIGTERM);
kill(getppid(),SIGTERM);
exit(0);
}
mesg_send(writefd,&mesg);
}
}
int main(int argc, char ** argv){
/*MAXMESGDATA== 92 bytes; sizeof(struct mymesg)== 100 bytes
2* sizeof(long)== 8 bytes; MESGHDRSIZE ==8 bytes*/
int readfd,writefd;
pid_t childpid;
//create 2 FIFOs
if ((mkfifo(FIFO1,FILE_MODE)<0) && (errno!=EEXIST)){
printf("can't create %s",FIFO1);
exit(1);
}
if ((mkfifo(FIFO2,FILE_MODE)<0) && (errno!=EEXIST)){
printf("can't create %s",FIFO1);
unlink(FIFO1);
exit(1);
}
if ((childpid=fork()==0)){//child
readfd=open(FIFO1,O_RDONLY,0);
writefd=open(FIFO2,O_WRONLY,0);
server(readfd,writefd);
exit(0);
}
//parent
writefd=open(FIFO1,O_WRONLY,0);
readfd=open(FIFO2,O_RDONLY,0);
client(readfd,writefd);
waitpid(childpid,NULL,0);
close(readfd);
close(writefd);
unlink(FIFO1);
unlink(FIFO2);
return EXIT_SUCCESS;
}

You open FIFO2 as WRONLY and FIFO1 as RDONLY in both the processes. Opening pipe for read will block until the other side opens for write, and you open for read on both sides - hence deadlocked.

Related

Problem Running Message Queue on two terminals

I am trying to run two processes which are basically sending and receiving messages using message queue(SYS V). While I can run two process on same terminal tab by keeping my receiver in background
./receiver &
and sender in the foreground.
./sender
which is working fine but causing all my prints from sender & receiver display on same tab.
If I try to run receiver on one terminal tab and sender on other terminal-tab, the processes are not working correctly, they fail to identify message queue exist on the system.
I am not sure if its the terminal issue, or my program issue, I am using MobaXterm terminal.
Added code below, Am I missing w.r.t running processes on two different terminals I would like to know.
receiver.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define PATH "/tmp/CMN_KEY"
struct message_text {
int qid;
char buf [200];
};
struct message {
long message_type;
struct message_text message_text;
};
int main (int argc, char **argv)
{
key_t key;
int qid;
struct message message;
if ((key = ftok (PATH,'Z')) == -1) {
printf ("ftok");
exit (1);
}
if ((qid = msgget (key, IPC_CREAT | 0660)) == -1) {
printf ("msgget");
exit (1);
}
printf ("Receiver: Waiting for MSG!\n");
while (1) {
// read an incoming message
if (msgrcv (qid, &message, sizeof (struct message_text), 0, 0) == -1) {
printf ("msgrcv");
exit (1);
}
printf ("Receiver: MSG Received.\n");
// message from sender
int length = strlen (message.message_text.buf);
char buf [20];
sprintf (buf, " %d", length);
strcat (message.message_text.buf, buf);
int client_qid = message.message_text.qid;
message.message_text.qid = qid;
// send reply message to Sender
if (msgsnd (client_qid, &message, sizeof (struct message_text), 0) == -1) {
printf ("msgget");
exit (1);
}
printf ("Receiver: Response sent to Sender .\n");
}
}
sender.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define PATH "/tmp/CMN_KEY"
struct message_text {
int qid;
char buf [200];
};
struct message {
long message_type;
struct message_text message_text;
};
int main (int argc, char **argv)
{
key_t key;
int sender_qid, myqid;
struct message my_message, return_message;
// queue for receiving messages from receiver
if ((myqid = msgget (IPC_PRIVATE, 0660)) == -1) {
printf ("msgget: myqid");
exit (1);
}
printf("Sender created q with ID: %d\n" , myqid);
if ((key = ftok (PATH,'Z')) == -1) {
printf ("ftok");
exit (1);
}
if ((sender_qid = msgget (key, 0)) == -1) {
printf ("msgget: sender_qid");
exit (1);
}
my_message.message_type = 1;
my_message.message_text.qid = myqid;
printf ("Input a message: ");
while (fgets (my_message.message_text.buf, 198, stdin)) {
int length = strlen (my_message.message_text.buf);
if (my_message.message_text.buf [length - 1] == '\n')
my_message.message_text.buf [length - 1] = '\0';
// send message to Receiver
if (msgsnd (sender_qid, &my_message, sizeof (struct message_text), 0) == -1) {
printf ("client: msgsnd");
exit (1);
}
// read response from Receiver
if (msgrcv (myqid, &return_message, sizeof (struct message_text), 0, 0) == -1) {
printf ("client: msgrcv");
exit (1);
}
// Return message from Receiver
printf ("Return Message From Receiver: %s\n\n", return_message.message_text.buf);
printf ("type a one more message: ");
}
// remove message queue
if (msgctl (myqid, IPC_RMID, NULL) == -1) {
printf ("client: msgctl");
exit (1);
}
return
}

TunTap Device receiving ping

I am trying to get familiar with tuntap devices. I have read the following article:
https://backreference.org/2010/03/26/tuntap-interface-tutorial/
but somehow the code from the article doesn't work.
I have this code:
#include <sys/socket.h> //well get our socket
#include <sys/ioctl.h> //thats our input output control
#include <sys/time.h>
#include <fcntl.h>
#include <asm/types.h> //these are data types liked signed unsingend
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> //read write close and stuff
#include <signal.h> //different signals
#include <linux/if_packet.h> //interface for packets
#include <linux/if_ether.h> //interface or ethernet frames
#include <linux/if_arp.h> //interface for arp
#include <linux/if.h>
#include <linux/if_tun.h>
#include <arpa/inet.h>
int tun_alloc(char *dev, int flags) {
struct ifreq ifr;
int fd, err;
char *clonedev = "/dev/net/tun";
/* Arguments taken by the function:
*
* char *dev: the name of an interface (or '\0'). MUST have enough
* space to hold the interface name if '\0' is passed
* int flags: interface flags (eg, IFF_TUN etc.)
*/
/* open the clone device */
if( (fd = open(clonedev, O_RDWR)) < 0 ) {
return fd;
}
/* preparation of the struct ifr, of type "struct ifreq" */
memset(&ifr, 0, sizeof(ifr));
ifr.ifr_flags = flags; /* IFF_TUN or IFF_TAP, plus maybe IFF_NO_PI */
if (*dev) {
/* if a device name was specified, put it in the structure; otherwise,
* the kernel will try to allocate the "next" device of the
* specified type */
strncpy(ifr.ifr_name, dev, IFNAMSIZ);
}
/* try to create the device */
if( (err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0 ) {
close(fd);
return err;
}
/* if the operation was successful, write back the name of the
* interface to the variable "dev", so the caller can know
* it. Note that the caller MUST reserve space in *dev (see calling
* code below) */
strcpy(dev, ifr.ifr_name);
/* this is the special file descriptor that the caller will use to talk
* with the virtual interface */
return fd;
}
int main(void){
unsigned int seconds = 1;
char tap_name[IFNAMSIZ];
strcpy(tap_name, "tun0");
printf("%s\n", tap_name);
int tap_fd = tun_alloc(tap_name, IFF_TUN);
void *buffer = (void *)(malloc(3000));
printf("%s\n", tap_name);
if(tap_fd < 0){
perror("Allocating interface");
exit(1);
}
int nread;
while(1){
nread = read(tap_fd, buffer, sizeof(buffer));
if (nread < 0){
perror("Nread: ");
close(tap_fd);
free(buffer);
exit(1);
}
printf("Read %d Bytes from devies %s \n", nread, tap_name);
sleep(seconds);
}
}
I executed this program on one terminal and pinged the interface from another terminal.
But when I ping the interface from the command line (ping 192.168.0.24, I have assigned that IP to the interface), on the terminal of the program there's always written "read 8 Bytes from interface", although the number of bytes should vary when I ping the interface. Does anyone see the mistake?

client/server print out array and write back

I am using C and putty to write a client/server program.
Both c files are on the same system.
I am currently having an issue with writing back to the client the frames it is using as well as printing out my frames. It prints out 3 0 9 8 but then it starts printing out 13456756 etc.
Here is what I have:
server:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
main (void)
{
int to_server; // to read from client
int from_server; // to write to client
int finish; // lets me know that client is done
int i,j,k,m,l; // because C needs this defined as int
int numClient;// number of clients
char temp[14];
int page_size = 128;
int pages_left;
int max_frames=10;
int used_frames =0;
int frameUpdate=0;
int freeframe[10] = {3,0,9,8,7,5,1,4,2,6}; //this is the array
int numpage=0;
int frames;
int check;
int option;
int byte;
int getPage;
int getOffset;
int physical_Addr;
int offset;
int req[3];
int again;
struct values{
char privFifo[14];
int memoryreq;
}cinput;
/* Create the fifos and open them */
if ((mkfifo("FIFO1",0666)<0 && errno != EEXIST))
{
perror("cant create FIFO1");
exit(-1);
}
if((to_server=open("FIFO1", O_RDONLY))<0){
printf("cant open fifo to write");
}
//get number of clients
printf("\nHow many clients?\n");
scanf("%d", &numClient);
for(j =1; j <= numClient; j++){
read(to_server, &cinput, sizeof(cinput));
printf("\n\nFifo_%d \nMemory request %d", &cinput.privFifo, cinput.memoryreq);
req[j-1] = cinput.memoryreq;
if((mkfifo(cinput.privFifo,0666)<0 && errno != EEXIST))
{
perror("cant create privFifo");
exit(-1);
}
if((from_server=open(cinput.privFifo, O_WRONLY)<0)){
printf("cant open fifo to write");
}
// find number of pages need for request
numpage = cinput.memoryreq/page_size;
if((numpage * page_size) < cinput.memoryreq){
numpage++;
}
sleep(1);
printf("\nPages needed %d", numpage);
write(from_server, &numpage, sizeof(numpage));
printf("\n******Main Memory******");
for(m = used_frames; m < numpage; m++){
printf("\n* client: %d\tframe: %d", j, freeframe[m]);
frames = freeframe[m];
write(from_server, &frames, sizeof(frames));
}
used_frames = max_frames - used_frames;
pages_left = max_frames - numpage;
//this is where I try to print out the available frames
printf("\n Frames available:");
for(l = pages_left; l!= 0; l--){
check = max_frames - l;
printf(" %d", freeframe[check]);
max_frames = check;
}
close(from_server);
unlink(cinput.privFifo);
}
printf("\nDONE!!!");
close(to_server);
unlink("FIFO1");
client:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
main (void)
{
int to_server; // to write to server
int from_server;
char temp[14]; // server puts string here
int clientID;
//int frames;
int numpage;
int i;
struct values{
char privFifo[14];
int memoryreq;
}cinput;
if((to_server=open("FIFO1", O_WRONLY))<0)
printf("cant open fifo to write\n");
printf("writing data to to_server\n");
printf("Client: Please enter number of memory units: ");
scanf("%d", &cinput.memoryreq);
printf("%d", cinput.memoryreq);
clientID = getpid();
sprintf(cinput.privFifo, "Fifo_%d", getpid());
printf("\nFifo name is %s", &cinput.privFifo);
write(to_server, &cinput, sizeof(cinput));//write client pid and memUnit to server
sleep(2); //give time to send
printf("\nClient: Got the character sent, now waiting for response ");
if ((mkfifo(cinput.privFifo,0666)<0 && errno != EEXIST))
{
perror("cant create FIFO1");
exit(-1);
}
if((from_server=open(cinput.privFifo, O_RDONLY))<0){
printf("cant open fifo to write");
}
read(from_server, &numpage, sizeof(numpage));
printf("\nFrames Occupied %d", numpage);
close(to_server);
close (from_server);
unlink(cinput.privFifo);
printf ("\nall done!\n");
}
Any help is greatly appreciated. Thank you.
I strongly suspect the problem is the line used_frames = max_frames - used_frames;. Since used_frames is initially 0, that sets it one past the end of the array for the second iteration, so you start printing values past the end of your frame array when you run for(m = used_frames; m < numpage; m++). (By the way: please indent properly.). But set a breakpoint and run in a debugger to be sure.

File sent over TCP is created with type: application/octet-stream

I'm trying to transfer a file from a server to a client using TCP protocol.
I manage to send the whole syze of the file, but when the client creates the file, it cant be open. In this case, im sending an jpg file.
heres the code for server.c:
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
#include <arpa/inet.h>
#define PORT 59000
int main(int argc,char *argv[]) {
int port, fd, newfd, n, nw, addrlen;
int port_was_given = 0;
char buffer[128], *ptr, *topic, *data;
size_t result;
struct hostent *h;
struct sockaddr_in addr;
FILE *send;
if((fd=socket(AF_INET,SOCK_STREAM,0))==-1)exit(1); //error
memset((void*)&addr,(int)'\0',sizeof(addr));
addr.sin_family=AF_INET;
addr.sin_addr.s_addr=htonl(INADDR_ANY);
if (argc == 3) {
port = atoi(argv[2]);
port_was_given = 1;
}
if(port_was_given == 1)
addr.sin_port=htons((u_short)port);
else
addr.sin_port=htons((u_short)PORT);
if(bind(fd,(struct sockaddr*)&addr,sizeof(addr))==-1)exit(1); //error
if(listen(fd,5)==-1)exit(1); //error
while(1) {
addrlen=sizeof(addr);
if((newfd=accept(fd,(struct sockaddr*)&addr,&addrlen))==-1)exit(1); //erro
h=gethostbyaddr((char*)&addr.sin_addr,sizeof(struct in_addr),AF_INET);
while((n=read(newfd,buffer,128))!=0) {
if(n==-1)exit(1);
topic = strtok(buffer," ");
topic = strtok(NULL," ");
if (strcmp(topic, "Nacional\n")==0) {
send = fopen("flag","r");
fseek(send, 0L, SEEK_END); //vai ate ao fim do ficheiro
int sz = ftell(send); //size of file
fseek(send,0L,SEEK_SET);
//rewind(send);
data = (char*)malloc(sizeof(char)*sz);
result = fread(data,1,sz,send);
//fseek(send,0L,SEEK_SET);
fclose(send);
char ptr2[300] = "REP ok ";
char *ptrInt; //for s -> int
sprintf(ptrInt, "%d", sz);
strcat(ptr2, ptrInt);
strcat(ptr2, " ");
strcat(ptr2, data);
strcat(ptr2, "\n");
while(n>0) {
nw=write(newfd,ptr2,n); //write n bytes on each cycle
}
}
}
close(newfd);
}
close(fd);
exit(0);
}
Ok so the logic is: client requests a type of content, in this case the content is "Nacional", so the server has to send the "flag.jpg" to the client.
The answer of the server has the following type:
REP status size data
In which status can be "ok" or "nok". If "nok" then the file is not sent.
size is the size of the data.
data is data of the file itself.
Now the client.c:
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
#include <arpa/inet.h>
#define PORT 58000
#define NG 10
int main (int argc,char *argv[])
{
/** ... variables declarations and other stuff ... */
fdtcp=socket(AF_INET,SOCK_STREAM,0);
if (fdtcp==-1) exit(1); // Erro
inet_aton(ip, &address);
if (strcmp(lsname, "localhost")==0)
newHost = gethostbyname("localhost");
else
newHost = gethostbyaddr((const void *)&address,sizeof ip,AF_INET);
newPort = atoi(newport);
memset((void*)&addrtcp,(int)'\0',sizeof(addrtcp));
addrtcp.sin_family=AF_INET;
addrtcp.sin_addr.s_addr=((struct in_addr *)(newHost->h_addr_list[0]))->s_addr;
addrtcp.sin_port=htons((u_short)newPort);
k = connect(fdtcp,(struct sockaddr*)&addrtcp,sizeof(addrtcp));
if (k==-1) exit(1); // Erro
// REQ Tn (Conteudo Solicitado)
ptr = strcat(reqdata, tn);
ptr = strcat(reqdata, "\n");
// Envia-se o Comando REQ
nreqleft = 25;
while(nreqleft>0) {
kwrite=write(fdtcp,ptr,nreqleft);
if (kwrite<=0) exit(1); // Erro
nreqleft -= kwrite;
ptr += kwrite;
}
// Recebe-se o Comando REP
nreqleft = 128;
ptr = &buffertcp[0];
kread=read(fdtcp,ptr,nreqleft);
if (kread==-1) exit(1); // Erro
cmd = strtok(buffertcp, " "); // REP
cmd = strtok(NULL, " "); // Status
if(strcmp(cmd,"ok")) {
printf("ERR\n");
exit(1); // Erro
}
cmd = strtok(NULL, " "); // Size
size = atoi(cmd);
// Recebem-se os Dados do Conteúdo Desejado
nreqleft = size;
char data[size];
ptr = &data[0];
while(nreqleft>0) {
kread=read(fdtcp,ptr,nreqleft);
if (kread==-1) exit(1); // Erro
nreqleft -= kread;
ptr += kread;
}
file = fopen("file","w");
fwrite(data, 1, size, file);
fclose(file);
close(fdtcp);
// --------------------------------------------------- //
exit(0);
}
The "other stuff" part is just variables declarations and a UDP connection with another server which has nothing to do with this part, so I'm 100% sure it won't affect this part. In fact, on client.c, if I place an printf of the message received from the server, it will show "REP ok 31800 ?????" which ??? I assume would be the data of the file.
The problem is that the "file" created can't be open. Help?
One problem is that 31800 is much larger than 300, and so when you append the data to your ptr2 array in the server, you have buffer overrun. You can correct that by not sending the data with a separate write() call after sending your "header" in ptr2. Your write() loop looks like it will loop forever, but I am guessing you are not showing all of your code.
In the receiver, I don't see any attempt to parse the header to separate the header from the data. Since you read in up to 128 bytes, that read may have received both the header and some data of the file, and you make no attempt to detect and save that part of the file.
When debugging file transfer applications, I would start with textual files so that you can visually see the resulting file, and run a simple diff on the file you saved with the actual file to see if there are differences.

Error "Bad address" when reading from message queue on Linux

I have assignment when I need to write simple time server and a client using Linux message queue. The server opens a message queue and the client sends a request with his PID (message with type 1) and the server reads that message and sends a message with type of PID (taken from the message read). I put all the code below because I don't know where I made the mistake. I'm not Linux programming expert. Don't even know if I written server correct.
File that is included by server and client (I need to write it in this way).
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/msg.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <string.h>
#include <signal.h>
#define QUEUE 100
#define PERM_ALL 0777
typedef struct my_msgbuf {
long mtype;
int pid;
} ClientMessage;
typedef struct my_msgbuf2 {
long mtype;
struct tm time;
} TimeMessage;
Server
int m_queue;
void cleanup(int signum) {
if (msgctl(m_queue, IPC_RMID, NULL) == -1) {
printf("Something happen on clean up\n");
exit(1);
}
exit(signum);
}
int main() {
ClientMessage pid_message;
TimeMessage t;
time_t clock;
struct tm *cur_time;
if ((m_queue = msgget(QUEUE, PERM_ALL | IPC_CREAT)) == -1) {
printf("Can't create and open message queue\n");
exit(1);
}
printf("created message queue = %d\n", m_queue);
fflush(stdout);
//t = malloc(sizeof(TimeMessage));
signal(SIGINT, cleanup);
while (1) {
if (msgrcv(m_queue, &pid_message, sizeof(pid_message.pid), 1, 0) == -1) {
break;
} else {
t.mtype = pid_message.pid;
clock = time(NULL);
cur_time = localtime(&clock);
memcpy(&t.time, cur_time, sizeof(struct tm));
msgsnd(m_queue, &t, sizeof(struct tm), 0);
}
}
cleanup(0);
}
Client
int main() {
int m_queue;
TimeMessage *t;
ClientMessage client;
if ((m_queue = msgget(QUEUE, PERM_ALL)) == -1) {
perror("Error in opening queue");
exit(1);
}
client.mtype = 1;
client.pid = getpid();
while (1) {
if (msgsnd(m_queue, &client, sizeof(client.pid), 0) == -1) {
perror("Error sending to queue");
exit(1);
} else {
if (msgrcv(m_queue, t, sizeof(struct tm), client.pid, 0) == -1) {
perror("Error reading from queue");
exit(1);
}
printf("time: %d:%d:%d\n", t->time.tm_hour, t->time.tm_min, t->time.tm_sec);
}
}
return 0;
}
Both program compile without errors but client return "Error reading from queue" msgrcv is returning -1.
After adding the perror it appears that you have got the error stating "Bad Address" (EFAULT) which means that "The address pointed to by msgp (buffer) isn't accessible". From the code it appears that there has been no memory allocated to TimeMessage *t so you can either allocate memory or just change it to TimeMessage t and pass &t instead of t to msgrcv. Also size should be sizeof t (assuming the change from *t to t, or sizeof(TimeMessage) for *t) instead of sizeof(struct tm) (& obviously you would change printf statement accordingly)
Hope this helps!

Resources