Monday, July 11, 2011

File Transaction Using Message Q's IPC

//message file transaction


    # include <stdio.h>
    # include <string.h>
    # include <sys/stat.h>
    # include <sys/msg.h>
    # include <sys/ipc.h>
    # include <sys/types.h>

    //message structure
   
    struct message
    {
    long msg_type;
    char msg_data[1024];
    };
    //global objects
    struct message msg_obj1={100,"I"};
    struct message msg_obj2={100,"M"};
    //global msg id
    int msg_id;
   
    //function to put file to message Q
    putToMessageQ(char*fn)
    {
    FILE*f;
    int x,y,i=0;
    char ch;
    if((f=fopen(fn,"r"))==NULL)
    perror("\nUnable to open file for reading...");
    else
    {
        while((ch=getc(f))!=EOF)
        {
        msg_obj1.msg_data[i++]=ch; //writing to msg_data
        }   
        fclose(f); //closing file
    }
       
    //creating msg q id
    if((msg_id=msgget(1234,IPC_CREAT|0644))==-1)
    perror("\nUnable to get message id...");
    else
    printf("\nmsgid=%d",msg_id);

    /*writing message to the q */
    if((x=msgsnd(msg_id,&msg_obj1,strlen(msg_obj1.msg_data),IPC_NOWAIT))==-1)
    perror("\nUnable to send message...");
    else
    printf("\nSend Msg Success : return %d",x);

    }

    //function to transfer the file

    getFromMessageQ(char*fn)
    {

    FILE*f;
    int x,y,i=0;
    char ch;

    /* rec message from q*/
    if((y=msgrcv(msg_id,&msg_obj2,15,100,MSG_NOERROR))==-1)
    perror(":- msgrcv error...");
    else
    printf("\nRec Bytes : %d",y);

    if((f=fopen(fn,"w"))==NULL)
    perror("\nUnable to open file for writing...");
    else
    {
        for(i=0;msg_obj2.msg_data[i]!=0;i++)
        {
        putc(msg_obj2.msg_data[i],f);
        }   
        fclose(f); //closing file
    }
    return 0;   
    }
       
   
    int main(int argc,char*argv[])
    {
    putToMessageQ(argv[1]);
    getFromMessageQ(argv[2]);
    return 0;   
    }


       
       

No comments:

Post a Comment