Friday, October 10, 2008



Lab exam question no.2

/*
Three process p1,p2 & p3.
p1 should read the msg thrgh keyboard and send it to a message queue.
p2 is to read msg frm the message queue and to reverse string.
now create a pipe and send the reversed string to the pipe
process p3 read the reversed string from the pipe
ok this is the question
*/

#include

#include

#include

#include

#include

#include

#define MSGSZ 128

/*

* Declare the message structure.

*/

typedef struct msgbuf {

long mtype;

char mtext[MSGSZ];

} message_buf;

main()

{

int pid;

int msqid; // Used to store the message queue id.

int msgflg = IPC_CREAT | 0666;

key_t key;

/* pointers to send and recieve message buffer.*/
message_buf sbuf,rbuf; 

size_t buf_length;

int fd[2],i;

char msg[20],temp;

/*

* Get the message queue id for the

* "name" 1234, which was created by

* the server.

*/

key = 1234; // A default key is used.

printf("In process 1\n\tEnter the message : ");
scanf("%s",sbuf.mtext);

/* Creating a message queue. */

printf("\n\tmsgget: Calling msgget(%#lx,\%#o)\n",key, msgflg);

if ((msqid = msgget(key, msgflg )) < 0) 
{

perror("\tmsgget");
exit(1);

}

else

printf("\tmsgget: msgget succeeded: msqid = %d\n", msqid);

/*

* We'll send message type 1

*/

sbuf.mtype = 1;

buf_length = strlen(sbuf.mtext) + 1 ;

/*

* Send a message.

*/

if (msgsnd(msqid, &sbuf, buf_length, IPC_NOWAIT) < 0) 
{

printf ("\n\t%d, %d, %s, %d\n", msqid, sbuf.mtype, sbuf.mtext, buf_length);
perror("\tmsgsnd");
exit(1);

}

else

printf("\n\tMessage: \"%s\" Sent\n", sbuf.mtext);

pipe(fd);

pid = fork(); // Create the process p2.

if(pid==0)
{

printf("\nIn process 2.\n");
/*

* Receive an answer of message type 1.

*/

if (msgrcv(msqid, &rbuf, MSGSZ, 1, 0) < 0) 
{

perror("\tmsgrcv");

exit(1);

}

/*

* Print the answer.

*/

printf("\tMessage recieved : %s\n", rbuf.mtext);

buf_length=buf_length-1; 

/* Reverse the message */

for(i=0;i{
temp = rbuf.mtext[i];
rbuf.mtext[i] = rbuf.mtext[buf_length-1-i];
rbuf.mtext[buf_length-1-i] = temp;
}
printf("\tWriting %s to a pipe.\n",rbuf.mtext);
write(fd[1],rbuf.mtext,buf_length);
}



if(pid > 0)
{
pid = fork(); // Create the process p3.

if(pid == 0)
{

printf("\nIn process 3.");

/*
Read from the pipe.
*/
read(fd[0],msg,buf_length-1);
msg[buf_length-1]='\0';
printf("\n\tMessage read from the pipe : %s\n",msg);
}
}


}



/*
A sample ouput.

aneesh@aneesh-desktop:~/programs$ ./a.out
In process 1
Enter the message : aneesh

msgget: Calling msgget(0x4d2,01666)
msgget: msgget succeeded: msqid = 0

Message: "aneesh" Sent

In process 2.
Message recieved : aneesh
Writing hseena to a pipe.

In process 3.
Message read from the pipe : hseena
aneesh@aneesh-desktop:~/programs$ 
*/

No comments: