All pastes #564418 Raw Edit

SOE Lab6 sv.c

public c v1 · immutable
·published 2007-06-13 16:13 UTC
rendered paste body
#include <sys/types.h>#include <sys/ipc.h>#include <sys/shm.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/msg.h>#include <signal.h>#include <sys/stat.h>#define MAXMESG 10typedef struct {    union { 	struct { 	    char ident[8];	    char wiad[24];	};	int ilosc;    };    int valid:1;} wiadomosc;int shid=-1, qid=-1, retcode = 0;void sigintr_handler (int sig) {    if (shid!=-1)	shmctl(shid,IPC_RMID,0);    if (qid!=-1)	msgctl(qid,IPC_RMID,0);        exit(retcode);};int main(void) {    wiadomosc *wiads;        shid = shmget(IPC_PRIVATE,MAXMESG*sizeof(wiadomosc),IPC_CREAT|S_IRUSR|S_IWUSR);    if (shid<0) {	perror("shmget");	return -1;    }        wiads = (wiadomosc *)shmat(shid,0,0);    if ((int)wiads == -1) {	perror("shmat");	retcode = -1;	sigintr_handler(0);    }        wiads->valid = 0;         qid = msgget(IPC_PRIVATE,IPC_CREAT|S_IRUSR|S_IWUSR);    if (qid < 0) {	perror("msgget");	retcode = -1;	sigintr_handler(0);    }        retcode = 0;    signal (SIGINT,sigintr_handler);    printf("Msgid = %d\n",qid);        while (1) {	struct{	    long int mtype;	    wiadomosc wiad;	} mymsg;	int n;		int ret = msgrcv(qid,&mymsg,sizeof(wiadomosc),0,0);		if (ret == -1){	    perror("msgrcv");	    retcode = -1;	    sigintr_handler(0);	} else if (ret < sizeof(wiadomosc)) {	    fprintf(stderr,"Warning: msg truncated\n");	    continue;	} else if (mymsg.mtype == 2) {	    for (n=0;(n < MAXMESG)&&(wiads[n].valid);n++)		if (strcmp(mymsg.wiad.ident,wiads[n].ident)==0)			printf("Wiadomosc od %s o tresci %s\n",wiads[n].ident,wiads[n].wiad);	    printf("--\n");	    	    continue;	} else if (mymsg.mtype == 3) {	    for (n=0;(n < MAXMESG)&&(wiads[n].valid) && n < mymsg.wiad.ilosc;n++)		    printf("Wiadomosc od %s o tresci %s\n",wiads[n].ident,wiads[n].wiad);	    printf("--\n");		    continue;        	} else if (mymsg.mtype != 1) {	    fprintf(stderr,"Warning: invalid msg type\n");                                     continue;	}		for (n=0;(n < MAXMESG)&&(wiads[n].valid);n++);		if (n>=MAXMESG) {	    fprintf(stderr,"Warning: no space in shmem - wrapping around\n");	    n = 0;	}		memcpy(&(wiads[n]),&mymsg.wiad,sizeof(wiadomosc));	wiads[n].valid = 1;	    };        return 0;}