3 * Author: Jan Vales (e0726236@student.tuwien.ac.at)
5 * Purpose: Server. Merges received file-stubs
\r
6 * Usage: gluefile -s <size> <filename>
\r
7 * Output: debuginfo only
\r
10 #define _SVID_SOURCE
\r
11 #define _XOPEN_SOURCE 600
20 #include <sys/types.h>
\r
21 #include <sys/ipc.h>
\r
22 #include <sys/msg.h>
\r
27 const char *szCommand = "<not yet set>"; /* cmd name */
28 volatile static int nQueueID = -1; /* message queue ID */
30 /* prints a usage message to stderr */
\r
31 void usage( void ) {
\r
32 (void) fprintf(stderr, "USAGE: %s -s <filesize> <filename>\n", szCommand);
\r
35 /* forward declaration */
\r
36 void errorHalt(char *msg);
\r
38 /* close queue if open */
\r
40 (void)fprintf(stderr, "CLEANUP\n");
\r
41 if(nQueueID == -1)return;
\r
42 if(msgctl(nQueueID, IPC_RMID, (void*) 0) == -1){
\r
44 errorHalt("Cannot remove message queue!");
\r
50 /* prints error messages if an error has occoured */
\r
51 void errorHalt(char* msg){
52 if(errno != 0)(void)fprintf(stderr, "%s: %s = %s\n", szCommand, msg, strerror(errno));
\r
53 else (void)fprintf(stderr, "%s: %s\n", szCommand, msg);
\r
58 /* handles signals */
\r
59 void Handler( int nSignal ) {
\r
64 /* main program; sends messages via msg-queue to the "server" */
\r
65 int main( int argc, char **argv ) {
75 while((c = getopt(argc, argv, "s:")) != EOF){
\r
77 case 's':filesize = strtol(optarg, 0, 0);
78 if(filesize < 1)errorHalt("Could not determine filesize or filesize 0 or negative!");
80 case '?': usage(); return 0;
81 default:assert(0); break;
\r
84 filename = argv[optind];
85 if(!filename)errorHalt("Filename not given!");
87 (void) signal(SIGINT, Handler);
\r
88 (void) signal(SIGTERM, Handler);
\r
89 (void) signal(SIGQUIT, Handler);
91 if((nQueueID = msgget( KEY, PERM | IPC_CREAT )) == -1 )errorHalt("Cannot create/access message queue!");
92 if((fp = fopen(filename,"w")) == NULL)errorHalt("ERROR while opening file");
96 /* receive file-stubs and merge them*/
97 for(; offset < filesize;){
98 (void)fprintf( stderr, "\nwaiting: fsize:%d curr.written:%d\n", filesize, offset);
99 if(msgrcv(nQueueID, &msg, (sizeof(msg)-sizeof(long)), -(offset+1), 0) == -1)errorHalt("Cannot read from message queue!");
101 /* get valid datalength */
103 for(;len < sizeof(msg.mData)+1;len++){
104 if(msg.mData[len] == 0)break;
106 (void)fprintf(stderr, "got msg: datalength:%d offset:%ld\n", len, msg.mType-1);
109 if((msg.mType-1 + len) > filesize){fprintf(stderr, "**filesize exceeded -> discard**\n"); continue;}
110 (void)memcpy(fdata+(msg.mType-1), msg.mData, len);
111 if((msg.mType-1 + len) > offset)offset = (msg.mType-1 + len);
115 /* write data to file*/
116 for(; offset < filesize;){
117 if(!fputc(fdata[offset++],fp))fprintf( stderr, "Cannot write to file!\n");
119 if(fclose(fp))errorHalt("Cannot close file!");