int main(int argc, char ** argv) { sendQueues = malloc(MAX_CLIENTS * sizeof(mqd_t)); recQueues = malloc(MAX_CLIENTS * sizeof(mqd_t)); clientIDs = malloc(MAX_CLIENTS * sizeof(char*)); handShakeQueue = createQueue(HANDSHAKEQUEUE); printf("Handshake queue created. Server running...\n"); //atexit(cleanUp); signal(SIGINT, cleanUp); int rec_Status; idMsg recId; char buff[128]; message msg; while (1) { sleep(1); rec_Status = msgrcv(handShakeQueue, &recId, sizeof(recId.id), 0, IPC_NOWAIT); if (rec_Status >= 0) { sprintf(buff, "%s", recId.id); int send_id = msgget(IPC_PRIVATE, IPC_CREAT | S_IRUSR | S_IWUSR | S_IWGRP); int rec_id = msgget(IPC_PRIVATE, IPC_CREAT | S_IRUSR | S_IWUSR | S_IWGRP); printf("rec=%d send=%d\n", rec_id, send_id); recId.mtype = SERVER; sprintf(recId.id, "%d", send_id); msgsnd(handShakeQueue, &recId, sizeof(recId.id), 0); sprintf(recId.id, "%d", rec_id); msgsnd(handShakeQueue, &recId, sizeof(recId.id), 0); sendQueues[sendQueues_size] = send_id; recQueues[sendQueues_size] = rec_id; clientIDs[sendQueues_size] = malloc(sizeof(char) * strlen(buff)); sprintf(clientIDs[sendQueues_size], "%s\n", buff); printf("Registering user %s.\n", buff); sendQueues_size++; } int i; for (i = 0; i < sendQueues_size; i++) { int rec_Status = msgrcv(recQueues[i], &msg, sizeof(msg.time) + sizeof(msg.to) + sizeof(msg.content), 0, IPC_NOWAIT); if (rec_Status >= 0) { int to = getQueue(msg.to); if (to != -1) { sprintf(msg.to, "%s", clientIDs[i]); } else { sprintf(msg.content, ">> Message could not be delivered, try later. <<<\n"); to = sendQueues[i]; } msg.mtype = SERVER; rec_Status = msgsnd(to, &msg, sizeof(msg.time) + sizeof(msg.to) + sizeof(msg.content) , 0); if (rec_Status < 0) { printf("Message could not be forwared, no such user.\n"); return 1; } } } } return 0; }
int max_ctx_rcvr_except_last_one() { int max_p = MAX_OPENS; int i; int rc; bool do_recover = true; int msgid; struct mymsgbuf msg_buf; #ifndef _AIX char tmpBuff[MAXBUFF]; char cmdToRun[MAXBUFF]; const char *configCmdP = "echo 10000000 > /sys/kernel/debug/powerpc/eeh_max_freezes"; #endif system("ipcrm -Q 0x1234 >/dev/null 2>&1"); for (i = 0; i < max_p-1; i++) { if (0 == fork()) { //child process rc = create_res_hndl_afu_reset(do_recover, false); exit(rc); } } if (0 == fork()) { rc = create_res_hndl_afu_reset(false, false); if (100 == rc) rc = 0; //it was expected to failed with 100 else rc=1; exit(rc); } //Wait for all all child to reach do_eeh() call. sleep(10); #ifdef _AIX printf("%d:.....MAIN: BOSS do EEH now manually.......\n",getpid()); #else char * manualEehP = getenv("MANUAL_EEH"); if ( NULL == manualEehP ) { printf("%d:.....MAIN: doing EEH now .......\n",getpid()); rc = diskToPCIslotConv(cflash_path, tmpBuff ); CHECK_RC(rc, "diskToPCIslotConv failed \n"); rc = prepEEHcmd( tmpBuff, cmdToRun); CHECK_RC(rc, "prepEEHcmd failed \n"); rc = system(configCmdP); if (rc) { g_error = -1; fprintf(stderr,"%d: Failed in %s \n",pid,configCmdP); } debug("%d ---------- Command : %s----------------\n",pid,cmdToRun); rc = system(cmdToRun); if (rc) { g_error = -1; fprintf(stderr,"%d: Failed in %s \n",pid,cmdToRun); } } else { printf("%d:.....MAIN: BOSS do EEH now manually.......\n",getpid()); } #endif sleep(10); // Let the max ctx recover before we proceed. printf("%d:.....MAIN: Hope EEH is done by now..\n",getpid()); //now create new ctx //send true argument means, do create a msg queue //and inform waiting last process to perform reattach if (0 == fork()) { pid=getpid(); printf("%d: process created to attach after eeh...\n",pid); msgid = msgget(key, IPC_CREAT | 0666); if (msgid < 0 ) { fprintf(stderr, "%d: msgget() failed before msgsnd()\n", pid); exit(-1); } if (msgrcv(msgid, &msg_buf, 2, 2, 0) < 0) { fprintf(stderr, "%d: msgrcv failed with errno %d\n", pid, errno); exit(-1); } printf("%d:OK Recover done now start new attach.......\n",pid); rc = create_res_hndl_afu_reset(true, true); exit(rc); } rc = wait4all(); printf("%d: rc for wait4all(): %d\n", getpid(), rc); system("ipcrm -Q 0x1234"); return rc; }
int main( int argc , char *argv[] ) { int shmid, shmflg, queID, msgStatus, lines_active; key_t shmkey, msgQueKey; shared_data *p; msgBuf msg; shmkey = SHMEM_KEY ; shmflg = IPC_CREAT | S_IRUSR | S_IWUSR /* | IPC_EXCL */ ; shmid = shmget( shmkey , SHMEM_SIZE , shmflg ); if (shmid == -1) { printf("\nFailed to create/find shared memory '0x%X'.\n", shmkey ); perror("Reason:"); exit(-1); } p = (shared_data *) shmat( shmid , NULL , 0 ); if (p == (shared_data *) -1) { printf ("\nFailed to attach shared memory id=%d\n" , shmid ); perror("Reason:"); exit(-1) ; } /* Create / Find the message queues */ msgQueKey = BASE_MAILBOX_NAME ; queID = msgget( msgQueKey , IPC_CREAT | 0600 ) ; /*rw. ... ...*/ if ( queID < 0 ) { printf("Failed to create mailbox %X. Error code=%d\n", msgQueKey , errno ) ; exit(-2) ; } lines_active = atoi(argv[1]); while (0 < lines_active) { //printf("LINES ACTIVE: %d\n", lines_active); /* now, wait for a message to arrive from the user process */ msgStatus = msgrcv( queID , &msg , MSG_INFO_SIZE , 1 , 0 ); if ( msgStatus < 0 ) { printf("failed to receive message from user process on queuid %d. error code=%d\n" , queID , errno ) ; sleep(3); exit(-2) ; } if (msg.info.is_done == 1) { lines_active--; printf("Factory ID: %d Total iterations: %d Total parts produced: %d\n", msg.info.factory_ID, msg.info.num_iters, msg.info.produced); } else { p->total += msg.info.num_parts; p->num_iters++; printf("Factory ID: %d Capacity: %d Parts produced: %d Duration: %d\n", msg.info.factory_ID, msg.info.capacity, msg.info.num_parts, msg.info.duration); } } if (sem_post(&(p->factory_lines_finished))) { perror("Failed to post factory_lines_finished semaphore"); exit(-1); } if (sem_wait(&(p->print_aggregates))) { perror("Failed to post factory_lines_finished semaphore"); exit(-1); } printf("\nTotal Items Produced: %d\n", p->total); sleep(5); return 0; }
int recibir(ColaIPC* ipc, long tipo) { return msgrcv(ipc->cola, &ipc->nodo, IPC_LONGITUD, tipo, 0); }
int do_ipc(int qid, struct msgbuf *buf, int flags) { int ipc_read; CFILE *fptr=NULL; float last_volume = volume; int l=0; ipc_read = msgrcv(qid,buf,16,0,flags | MSG_NOERROR); switch (ipc_read) { case -1: if (errno == ENOMSG) break; perror("IPC trouble"); break; case 0: break; default: printf ("do_ipc %s\n", buf->mtext);//##########3 switch (buf->mtext[0]) { case 'v': volume=(double) (atof(buf->mtext+1)/128.0); printf("vol %f->%f\n",last_volume,volume); if (last_volume<=0 && volume>0) { buf->mtext[0]='p';//start playing again if volume raised above 0 strcpy(buf->mtext+1, digi_last_midi_song); //fall through to case 'p' }else if (last_volume>0 && volume<=0) { strcpy(buf->mtext, "s"); //stop playing if volume reduced to 0 stop = 2; break; }else break; case 'p': if (buf->mtext[1]) { strcpy(digi_last_midi_song, buf->mtext+1); if (volume>0) fptr=cfopen((buf->mtext+1),"rb"); } if(fptr != NULL) { l = cfilelength(fptr); data=realloc(data,(size_t) l); cfread(data, l, 1, fptr); cfclose(fptr); printf ("good. fpr=%p l=%i data=%p\n", fptr, l, data);//##########3 stop = 0; } else { strcpy(buf->mtext, "s"); //not playing, thus "stop". stop = 2; } break; case 's': stop = 2; break; case 'q': // SDL_KillThread(player_thread); break; } // printf ("do_ipc %s ret %i\n", buf->mtext, ipc_read);//##########3 } return ipc_read; }
int main(int argc, char *argv[]) { struct requestMsg req; struct responseMsg resp; int serverId, numMsgs; ssize_t msgLen, totBytes; if (argc != 2 || strcmp(argv[1], "--help") == 0) usageErr("%s pathname\n", argv[0]); if (strlen(argv[1]) > sizeof(req.pathname) - 1) cmdLineErr("pathname too long (max: %ld bytes)\n", (long) sizeof(req.pathname) - 1); /* Get server's queue identifier; create queue for response */ serverId = msgget(SERVER_KEY, S_IWUSR); if (serverId == -1) errExit("msgget - server message queue"); clientId = msgget(IPC_PRIVATE, S_IRUSR | S_IWUSR | S_IWGRP); if (clientId == -1) errExit("msgget - client message queue"); if (atexit(removeQueue) != 0) errExit("atexit"); /* Send message asking for file named in argv[1] */ req.mtype = 1; /* Any type will do */ req.clientId = clientId; strncpy(req.pathname, argv[1], sizeof(req.pathname) - 1); req.pathname[sizeof(req.pathname) - 1] = '\0'; /* Ensure string is terminated */ if (msgsnd(serverId, &req, REQ_MSG_SIZE, 0) == -1) errExit("msgsnd"); /* Get first response, which may be failure notification */ msgLen = msgrcv(clientId, &resp, RESP_MSG_SIZE, 0, 0); if (msgLen == -1) errExit("msgrcv"); if (resp.mtype == RESP_MT_FAILURE) { printf("%s\n", resp.data); /* Display msg from server */ exit(EXIT_FAILURE); } /* File was opened successfully by server; process messages (including the one already received) containing file data */ totBytes = msgLen; /* Count first message */ for (numMsgs = 1; resp.mtype == RESP_MT_DATA; numMsgs++) { msgLen = msgrcv(clientId, &resp, RESP_MSG_SIZE, 0, 0); if (msgLen == -1) errExit("msgrcv"); totBytes += msgLen; } printf("Received %ld bytes (%d messages)\n", (long) totBytes, numMsgs); exit(EXIT_SUCCESS); }
/* handle_ipc_request -- accept a request from a client, pass the request on to the XEmacs process, then wait for its reply and pass that on to the client. */ void handle_ipc_request (struct msgbuf *msgp) { struct msqid_ds msg_st; /* message status */ char buf[GSERV_BUFSZ]; int len; /* length of message / read */ int s, result_len; /* tag fields on the response from emacs */ int offset = 0; int total = 1; /* # bytes that will actually be sent off */ if ((len = msgrcv (ipc_qid, msgp, GSERV_BUFSZ - 1, 1, 0)) < 0) { perror (progname); fprintf (stderr, "%s: unable to receive\n", progname); ipc_exit (1); } /* if */ msgctl (ipc_qid, IPC_STAT, &msg_st); strncpy (buf, msgp->mtext, len); buf[len] = '\0'; /* terminate */ printf ("%d %s", ipc_qid, buf); fflush (stdout); /* now for the response from gnu */ msgp->mtext[0] = '\0'; #if 0 if ((len = read(0,buf,GSERV_BUFSZ-1)) < 0) { perror (progname); fprintf (stderr, "%s: unable to read\n", progname); ipc_exit (1); } /* if */ sscanf (buf, "%d:%[^\n]\n", &junk, msgp->mtext); #else /* read in "n/m:" (n=client fd, m=message length) */ while (offset < (GSERV_BUFSZ-1) && ((len = read (0, buf + offset, 1)) > 0) && buf[offset] != ':') { offset += len; } if (len < 0) { perror (progname); fprintf (stderr, "%s: unable to read\n", progname); exit(1); } /* parse the response from emacs, getting client fd & result length */ buf[offset] = '\0'; sscanf (buf, "%d/%d", &s, &result_len); while (result_len > 0) { if ((len = read(0, buf, min2 (result_len, GSERV_BUFSZ - 1))) < 0) { perror (progname); fprintf (stderr, "%s: unable to read\n", progname); exit (1); } /* Send this string off, but only if we have enough space */ if (GSERV_BUFSZ > total) { if (total + len <= GSERV_BUFSZ) buf[len] = 0; else buf[GSERV_BUFSZ - total] = 0; send_string(s,buf); total += strlen(buf); } result_len -= len; } /* eat the newline */ while ((len = read (0,buf,1)) == 0) ; if (len < 0) { perror(progname); fprintf (stderr,"%s: unable to read\n", progname); exit (1); } if (buf[0] != '\n') { fprintf (stderr,"%s: garbage after result [%c]\n", progname, buf[0]); exit (1); } #endif /* Send a response back to the client. */ msgp->mtype = msg_st.msg_lspid; if (msgsnd (ipc_qid,msgp,strlen(msgp->mtext)+1,0) < 0) perror ("msgsend(gnuserv)"); } /* handle_ipc_request */
void *File_Process(void *arg) { pthread_detach(pthread_self()); // add by andy for more info THREAD_INFO *tinfo = (THREAD_INFO *)arg; //mqid = (int)arg; mqid = tinfo->mqid; struct threadpool *pool = tinfo->pool; PRINTF(LEVEL_INFORM,"thread mqid = %d \n",mqid); //fprintf(stderr,"--->test = %d \n",test); //init thread share info MUTEX_SETUP(share_info.lock); share_info.dir1 = strdup(tinfo->dir1); share_info.dir2 = strdup(tinfo->dir2); share_info.app_name = strdup(tinfo->app_name); share_info.move_file = tinfo->move_file; share_info.m_addr = tinfo->m_addr; share_info.m_sock = Socket(AF_INET,SOCK_DGRAM,0); int fd; FILE *fp; struct msgbuf *buff = malloc(MAXMSG); int n , ret; mode_t fdmode = (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); int wlen; long long pack_total; long long pack_saved; long long pack_move; char *msg = NULL; //char save_path[512] ={0}; //add by andy ,fix bug tcp_echo err ,2014-12-12 char save_path[1024] ={0}; /**UDP 数据包结构**/ char protocol; long long file_size; int file_name_length; char *file_name; int pack_length; char *pack; again: pack_saved = 0; pack_move = 1; pack_total = 10; //这句可能是多余的 memset(buff,0,MAXMSG); while(1) { if((n = msgrcv(mqid,buff,MAXMSG,pack_move,IPC_NOWAIT)) < 0) //if((n = msgrcv(mqid,buff,MAXMSG,pack_move,0)) < 0) { n = msgrcv(mqid,buff,MAXMSG,0,0); if(n < 0) { //PRINTF(LEVEL_ERROR,"thread msgrcv error :%s\n",strerror(errno)); //WriteSysLog(LOG_PATH,log); goto err_end; continue; } pack_move = buff->mtype; } pack_move ++; msg = buff->mtext; if((pack_saved == 0)||(pack_move == 2)) { if((pack_move == 2)&&(pack_saved !=0)) { //PRINTF(LEVEL_ERROR,"A file is incomplete because client stop transmite by accident\n"); // write log pack_saved = 0; if(fp != NULL) { fclose(fp); fp = NULL; } } memcpy(&file_size,msg+10,8); pack_total = file_size/1024; if(file_size%1024 != 0) pack_total+=1; memcpy(&file_name_length,msg+18,4); file_name = (char *)malloc(file_name_length+1); memcpy(file_name,msg+22,file_name_length); *(file_name+file_name_length) = '\0'; // usr dir install of true path ,andy,2015-03-07 //sprintf(save_path,RUN_PATH); //strcat(save_path,file_name); sprintf(save_path,"%s/%s/",tinfo->dir1,tinfo->app_name); strcat(save_path,basename(file_name)); //memcpy(&pack_length,msg+22+file_name_length,4); pack = msg +22 +file_name_length +4; ret = CreateDir(save_path); if(ret < 0) { ; } fp = fopen(save_path,"w+"); if(fp == NULL) { PRINTF(LEVEL_ERROR,"Open %s error:%s",file_name,strerror(errno)); goto err_end; } } memcpy(&pack_length,msg+22+file_name_length,4); int n = fwrite(pack,sizeof(char),pack_length,fp); if(n != pack_length) { PRINTF(LEVEL_ERROR,"Write %s error :%s\n",file_name,strerror(errno)); goto err_end; } pack_saved++; /**写文件成功,记录**/ //检查文件大小 if(pack_total == pack_saved ) { //PRINTF(LEVEL_ERROR,"Last Pack Size :%d\n",pack_length); fclose(fp); fp = NULL; threadpool_add_job(pool,Recv_Finish,save_path); //tcp_echo(save_path,strlen(save_path),t_sockfd); free(file_name); goto again; } else if(pack_total == (pack_move -1)) { //PRINTF(LEVEL_ERROR,"## lost package ## File %s is incomplete\n",file_name); fclose(fp); fp = NULL; //remove(save_path); //tcp_echo(save_path,strlen(save_path),t_sockfd); free(file_name); goto again; } } err_end: free(buff); free(file_name); exit(-1); return NULL; }
int main() { int id_msg; key_t clef; msg message; int msg_size; int num_client; clef = ftok("./sr03p020", 0); if (clef == -1) { perror("Erreur obtention clef"); perror("ftok()"); exit(EXIT_FAILURE); } id_msg = msgget(clef, 0); if(id_msg == -1) { perror("Erreur creation de la file de message impossible\n"); perror("msget()"); exit(EXIT_FAILURE); } //client envoie un premier message au serveur pour demander un identifiant //la taille du message devra etre une constante (pour simplifier) msg_size = sizeof(msg) - sizeof(long); message.type = REQ_SRV; message.req = DEM_NUM_CLT; msgsnd(id_msg, (void*)&message, msg_size, 0); msgrcv(id_msg, (void*)&message, msg_size, REP_NUM_CLT, 0); num_client = message.num_client; if (num_client == -1) { perror("Nombre maximum de clients (simultanés) atteint"); exit(EXIT_FAILURE); } int selection = 0; do { printf("\n\n########## CLIENT n° %d #########", num_client); printf("\n1 - Créer un panier"); printf("\n2 - Liste des objets disponibles"); printf("\n3 - Informations sur un objet"); printf("\n0 - Quit"); printf("\nEnter a selection: "); scanf("%d", &selection ); switch(selection) { case 0: message.req = CLT_LEAVE; message.type = REQ_SRV; msgsnd(id_msg, (void*)&message, msg_size, 0); msgrcv(id_msg, (void*)&message, msg_size, num_client, 0); printf("\nClient quit properly\n"); exit(0); break; case 1: message.req = DEM_PANIER; message.type = REQ_SRV; msgsnd(id_msg, (void*)&message, msg_size, 0); msgrcv(id_msg, (void*)&message, msg_size, num_client, 0); printf("\nPanier créé\n"); break; case 2: message.req = DEM_LISTE; message.type = REQ_SRV; msgsnd(id_msg, (void*)&message, msg_size, 0); msgrcv(id_msg, (void*)&message, msg_size, num_client, 0); printf("\nRéponse : %s", message.list_objects); break; case 3: message.req = DEM_INFOS; message.type = REQ_SRV; int selection_objet = 0; do { printf("\nEntrez le numéro de l'objet"); printf("\n1 - Banane"); printf("\n2 - Pomme"); printf("\n3 - Poire"); printf("\nEnter a selection: "); scanf("%d", &selection_objet ); } while (selection_objet < 1 && selection_objet > 3); message.num_object = selection_objet; msgsnd(id_msg, (void*)&message, msg_size, 0); msgrcv(id_msg, (void*)&message, msg_size, num_client, 0); printf("\nRéponse : Prix : %d, Stock: %d", message.object_price, message.object_qty); break; } } while (1); }
ssize_t messageQueueRecv(msgbuf_struct *msg) { return msgrcv(msgid, msg, MSG_STRUCT_SIZE, 1, 0); }
void HandleScreen(int _msqid) { int msqid = _msqid; int width, height; int curx = 0, cury = 0; textmsg msg; InitCurses(); pthread_mutex_lock(&count_mutex); pthread_cond_signal(&count_threshold_cv); pthread_mutex_unlock(&count_mutex); getmaxyx(stdscr, height, width); class CursesWindow inputWin, tmpWin; inputWin.set(InitializeScreen(0, (height/2), width, height/2, false)); tmpWin.set(InitializeScreen(0, 0, width, height/2, true)); class CursesListWindow outputWin(tmpWin); while(true) { if (msgrcv(msqid, &msg, sizeof(msg) - sizeof(long), TYPE_QUIT, IPC_NOWAIT) == -1) { if (msgrcv(msqid, &msg, sizeof(msg) - sizeof(long), TYPE_MSG, IPC_NOWAIT) == -1) { continue; } if (msg.mwindow == WINDOW_INPUT) { if ((msg.mproperties & PROP_CLEAR) == PROP_CLEAR) { inputWin.clear(); } if((msg.mproperties & PROP_DEL) == PROP_DEL) { inputWin.deleteChar(); } else { if ((msg.mproperties & (PROP_TOP | PROP_BOTTOM)) == (PROP_TOP | PROP_BOTTOM)) { continue; } else if ((msg.mproperties & PROP_TOP) == PROP_TOP) { inputWin.move(0, 1); } else if ((msg.mproperties & PROP_BOTTOM) == PROP_BOTTOM) { inputWin.move(0, inputWin.getHeight() - 1); } inputWin.stdWrite(msg.mtext); } getyx(inputWin.getWindow(), cury, curx); inputWin.setCursorx(curx); inputWin.setCursory(cury); inputWin.refresh(); } else if (msg.mwindow == WINDOW_OUTPUT) { outputWin.clear(); outputWin.move(0, 0); outputWin.stdWrite(msg.mtext); getyx(outputWin.getWindow(), cury, curx); outputWin.setCursorx(curx); outputWin.setCursory(cury); outputWin.drawBottomLine(); outputWin.refresh(); } } else { break; } } // cleaning up endwin(); pthread_exit(NULL); }
void captain() { sleep(3); int numberOfLoadsTransported = 0; while(numberOfLoadsTransported < 10) { //begin loading ferry printf("Ferry is ready to load\n"); message.mtype = FERRY_READY_TO_LOAD; msgsnd(idMessageFromCaptain, &message, messageLength, 0); msgrcv(idMessageVehicleToCaptain, &message, messageLength, FERRY_READY_TO_LOAD_ACK, 0); //swap arrival and late arrival queue ids because vehicles do this int temp = idMessageVehicleArrivalQueue; idMessageVehicleArrivalQueue = idMessageVehicleLateArrivalQueue; idMessageVehicleLateArrivalQueue = temp; int fullSpotsOnFerry = 0; int numTrucksOnFerry = 0; //ready to load vehicles, first load as many trucks as possible from the loading queue while(numTrucksOnFerry < 2 && msgrcv(idMessageVehicleLoadingQueue, &message, messageLength, TRUCK_READY_TO_LOAD, IPC_NOWAIT) != -1) { //truck available, tell it to load message.mtype = START_LOADING_TRUCK; printf("Begin loading truck number %d\n", message.vehicleId); msgsnd(idMessageFromCaptain, &message, messageLength, 0); numTrucksOnFerry++; fullSpotsOnFerry += 2; } //load as many cars as possible from loading queue while(fullSpotsOnFerry < 6 && msgrcv(idMessageVehicleLoadingQueue, &message, messageLength, CAR_READY_TO_LOAD, IPC_NOWAIT) != -1) { //car available, tell it to load message.mtype = START_LOADING_CAR; printf("Begin loading car number %d\n", message.vehicleId); msgsnd(idMessageFromCaptain, &message, messageLength, 0); fullSpotsOnFerry += 1; } //if ferry isn't fully loaded, accept the late cars into ferry //the late cars should have arrived into the late arrival queue while(fullSpotsOnFerry < 6) { //look for trucks if theres room for trucks if(numTrucksOnFerry < 2 && fullSpotsOnFerry < 5 && msgrcv(idMessageVehicleArrivalQueue, &message, messageLength, TRUCK_IN_ARRIVAL_QUEUE, IPC_NOWAIT) != -1) { printf("Begin loading LATE ARRIVAL truck number %d\n", message.vehicleId); message.mtype = START_LOADING_TRUCK; msgsnd(idMessageFromCaptain, &message, messageLength, 0); numTrucksOnFerry++; fullSpotsOnFerry += 2; } else if(msgrcv(idMessageVehicleArrivalQueue, &message, messageLength, CAR_IN_ARRIVAL_QUEUE, IPC_NOWAIT) != -1) { printf("Begin loading LATE ARRIVAL car number %d\n", message.vehicleId); message.mtype = START_LOADING_CAR; msgsnd(idMessageFromCaptain, &message, messageLength, 0); fullSpotsOnFerry += 1; } } //wait for confirmation messages printf("Confirming that vehicles have loaded.\n"); fullSpotsOnFerry = 0; while(fullSpotsOnFerry < 6) { if(msgrcv(idMessageVehicleToCaptain, &message, messageLength, FINISH_LOADING_CAR, IPC_NOWAIT) != -1) { printf("Captain knows car number %d has finished loading.\n", message.vehicleId); fullSpotsOnFerry++; } if(msgrcv(idMessageVehicleToCaptain, &message, messageLength, FINISH_LOADING_TRUCK, IPC_NOWAIT) != -1) { printf("Captain knows truck number %d has finished loading.\n", message.vehicleId); fullSpotsOnFerry += 2; } } printf("All vehicles have been loaded. Informing port that ferry is fully loaded and ready to sail.\n"); message.mtype = FERRY_FINISHED_LOADING; msgsnd(idMessageFromCaptain, &message, messageLength, 0); msgrcv(idMessageVehicleToCaptain, &message, messageLength, FERRY_FINISHED_LOADING_ACK, 0); printf("The ferry has left the port.\n"); sleep(3); printf("Ferry has arrived at the destination.\n"); message.mtype = FERRY_ARRIVED_AT_DESTINATION; msgsnd(idMessageFromCaptain, &message, messageLength, 0); msgrcv(idMessageVehicleToCaptain, &message, messageLength, FERRY_ARRIVED_AT_DESTINATION_ACK, 0); //unload trucks and cars //first unload all the trucks while(numTrucksOnFerry > 0) { printf("start unloading a truck from the ferry\n"); message.mtype = START_UNLOADING_TRUCK; msgsnd(idMessageFromCaptain, &message, messageLength, 0); numTrucksOnFerry -= 1; fullSpotsOnFerry -= 2; } while(fullSpotsOnFerry > 0) { printf("start unloading a car from the ferry\n"); message.mtype = START_UNLOADING_CAR; msgsnd(idMessageFromCaptain, &message, messageLength, 0); fullSpotsOnFerry -= 1; } //await confirmation of unloaded vehicles while(fullSpotsOnFerry < 6) { if(msgrcv(idMessageVehicleToCaptain, &message, messageLength, FINISH_UNLOADING_TRUCK, IPC_NOWAIT) != -1) { printf("captain knows a truck finished unloading.\n"); fullSpotsOnFerry += 2; } if(msgrcv(idMessageVehicleToCaptain, &message, messageLength, FINISH_UNLOADING_CAR, IPC_NOWAIT) != -1) { printf("captain knows a car finished unloading.\n"); fullSpotsOnFerry += 1; } } printf("Captain knows ship has finished unloading.\n"); printf("Informing port that the ferry finished unloading and is ready to return.\n"); message.mtype = FERRY_FINISHED_UNLOADING; msgsnd(idMessageFromCaptain, &message, messageLength, 0); msgrcv(idMessageVehicleToCaptain, &message, messageLength, FERRY_FINISHED_UNLOADING_ACK, 0); printf("Ferry sets sail.\n"); sleep(3); printf("Ferry has returned to port.\n"); message.mtype = FERRY_RETURNED; msgsnd(idMessageFromCaptain, &message, messageLength, 0); msgrcv(idMessageVehicleToCaptain, &message, messageLength, FERRY_RETURNED_ACK, 0); numberOfLoadsTransported++; printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); printf("FERRY HAS FINISHED TRANSPORTING %d LOADS.\n", numberOfLoadsTransported); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); /* printf("Captain says terminate.\n"); message.mtype = EXIT; msgsnd(idMessageFromCaptain, &message, messageLength, 0); break; */ } printf("The ferry has transported 10 loads and has returned for the 11th.\n"); /* while(forever) { break up the loop as follows top of the loop is for when ferry is at the dock, ready to load middle of loop is when ferry is loading vehicles middle part 2 of lopo is when ferry is unloading at the destination end of loop is when ferry is returning send message to vehicles that ferry is loading wait for acknowledgement time to begin loading go through trucks in loading queue and load up to two go through cars in loading queue and load as many as possible while there is still free space in ferry go through arrivalQueue (which should have switched with the lateArrivalQueue) load as many trucks as possible to fill missing trucks load as many cars as possible send message that ferry is done loading wait for acknowledgement begin sailing, sleep for however long arrived at destination, send message wait for acknowledgement send message to unload a vehicle, wait for acknowledgement from each one send message indicating unloading is complete wait for acknowledgement begin returning, lseep for however long send message indicating ferry has returned wait for acknowledgement } */ }
void vehicle() { //calculate interval between vehicle spawns, in seconds float nextVehicleSpawnTime = (rand() % maxTimeBetweenArrivals) / 1000.f; struct timeval timeOfLastVehicleSpawn; gettimeofday(&timeOfLastVehicleSpawn, 0); int vehicleId = 1; while(1) { if(msgrcv(idMessageFromCaptain, &message, messageLength, EXIT, IPC_NOWAIT) != -1) { printf("Terminated\n"); //captain says kill program, send acknowledgement msgsnd(idMessageVehicleToCaptain, &message, messageLength, 0); return; } float elapsedTimeSinceLastSpawn = calculateElapsedTime(timeOfLastVehicleSpawn); //check if its time to spawn a vehicle if(elapsedTimeSinceLastSpawn > nextVehicleSpawnTime) { //determine whether we should spawn a truck or a car int spawnNumber = rand() % 100 + 1; message.vehicleId = vehicleId++; //spawn a truck if(spawnNumber <= probabiltyOfTruckArriving) { //place truck in arrival lane message.mtype = TRUCK_IN_ARRIVAL_QUEUE; msgsnd(idMessageVehicleArrivalQueue, &message, messageLength, 0); printf("Truck number %d has arrived at the dock.\n", message.vehicleId); } else {//spawn a car message.mtype = CAR_IN_ARRIVAL_QUEUE; msgsnd(idMessageVehicleArrivalQueue, &message, messageLength, 0); printf("Car number %d has arrived at the dock.\n", message.vehicleId); } nextVehicleSpawnTime = (rand() % maxTimeBetweenArrivals) / 1000.f; gettimeofday(&timeOfLastVehicleSpawn, 0); } //check if captain wants ferry to load if(msgrcv(idMessageFromCaptain, &message, messageLength, FERRY_READY_TO_LOAD, IPC_NOWAIT) != -1) { //move all vehicles to loading queue while(msgrcv(idMessageVehicleArrivalQueue, &message, messageLength, TRUCK_IN_ARRIVAL_QUEUE, IPC_NOWAIT) != -1) { message.mtype = TRUCK_READY_TO_LOAD; msgsnd(idMessageVehicleLoadingQueue, &message, messageLength, 0); printf("Truck number %d is ready for loading.\n", message.vehicleId); } while(msgrcv(idMessageVehicleArrivalQueue, &message, messageLength, CAR_IN_ARRIVAL_QUEUE, IPC_NOWAIT) != -1) { message.mtype = CAR_READY_TO_LOAD; msgsnd(idMessageVehicleLoadingQueue, &message, messageLength, 0); printf("Car number %d is ready for loading.\n", message.vehicleId); } printf("Swapping arrival queue and late arrival queue.\n"); /*swap the arrival queue and the late arrival queue. the queues are swaped here, instead of after the ferry finishes loading because if a vehicle arrives while the ferry is loading it needs to go to the late arrival queue, which means a separate flag needs to be checked when a vehicle arrives in order to determine if the vehicle should be placed into the arrival queue, or the late arrival queue. if we swap the queues here then we can always put new vehicles in the arrival queue since late arrivals automatically end up in an empty queue*/ int temp = idMessageVehicleArrivalQueue; idMessageVehicleArrivalQueue = idMessageVehicleLateArrivalQueue; idMessageVehicleLateArrivalQueue = temp; //tell captain vehicles are ready for loading message.mtype = FERRY_READY_TO_LOAD_ACK; msgsnd(idMessageVehicleToCaptain, &message, messageLength, 0); } //if captain calls a vehicle to load, then send a confirmation if(msgrcv(idMessageFromCaptain, &message, messageLength, START_LOADING_TRUCK, IPC_NOWAIT) != -1) { message.mtype = FINISH_LOADING_TRUCK; msgsnd(idMessageVehicleToCaptain, &message, messageLength, 0); printf("Loaded truck number %d into the ferry.\n", message.vehicleId); } if(msgrcv(idMessageFromCaptain, &message, messageLength, START_LOADING_CAR, IPC_NOWAIT) != -1) { message.mtype = FINISH_LOADING_CAR; msgsnd(idMessageVehicleToCaptain, &message, messageLength, 0); printf("Loaded Car number %d into the ferry.\n", message.vehicleId); } if(msgrcv(idMessageFromCaptain, &message, messageLength, FERRY_FINISHED_LOADING, IPC_NOWAIT) != -1) { printf("Confirming ferry finished loading\n"); message.mtype = FERRY_FINISHED_LOADING_ACK; msgsnd(idMessageVehicleToCaptain, &message, messageLength, 0); } if(msgrcv(idMessageFromCaptain, &message, messageLength, FERRY_ARRIVED_AT_DESTINATION, IPC_NOWAIT) != -1) { printf("confirming ferry arrived at destination\n"); message.mtype = FERRY_ARRIVED_AT_DESTINATION_ACK; msgsnd(idMessageVehicleToCaptain, &message, messageLength, 0); } //received request to unload a vehicle, send confirmation if(msgrcv(idMessageFromCaptain, &message, messageLength, START_UNLOADING_TRUCK, IPC_NOWAIT) != -1) { message.mtype = FINISH_UNLOADING_TRUCK; msgsnd(idMessageVehicleToCaptain, &message, messageLength, 0); printf("Unloaded a truck\n"); } if(msgrcv(idMessageFromCaptain, &message, messageLength, START_UNLOADING_CAR, IPC_NOWAIT) != -1) { message.mtype = FINISH_UNLOADING_CAR; msgsnd(idMessageVehicleToCaptain, &message, messageLength, 0); printf("Unloaded a car\n"); } if(msgrcv(idMessageFromCaptain, &message, messageLength, FERRY_FINISHED_UNLOADING, IPC_NOWAIT) != -1) { printf("Confirming ferry finished unloading.\n"); message.mtype = FERRY_FINISHED_UNLOADING_ACK; msgsnd(idMessageVehicleToCaptain, &message, messageLength, 0); } if(msgrcv(idMessageFromCaptain, &message, messageLength, FERRY_RETURNED, IPC_NOWAIT) != -1) { printf("Confirming ferry has returned.\n"); message.mtype = FERRY_RETURNED_ACK; msgsnd(idMessageVehicleToCaptain, &message, messageLength, 0); } } /* create a timer while(forever) { if captain sends terminate message send acknowledgement exit if its time to spawn a vehicle determine what type of vehicle to spawn spawn vechicle by sending message to vechileArrivalQueue reset spawn timer if captain says ferry is ready to load move vehicles from arrivalQueue to loading queue swap the arrival queue and the late arrival queue the queues are swaped here, instead of after the ferry finishes loading because if a vehicle arrives while the ferry is loading it needs to go to the late arrival queue, which means a separate flag needs to be checked when a vehicle arrives in order to determine if the vechile should be placed into the arrival queue, or the late arrival queue. if we swap the queues here then we can always put new vehicles in the arrival queue since late arrivals automatically end up in an empty queue tell captain the vehicles are ready to load if a message to load a vechile arrives send a confirmation indicating the vehicle finished loading if captain says the ferry finished loading send a confirmation that message was received if captin says ferry arrived at destination send a confirmation that message was received if captain says to unload a vechile send a confirmation indicating the vehicle unloaded if captain says ferry finished unloading send confirmation if captain says the ferry has returned send confirmation } */ }
int main(int argc, char *argv[]) { char mostrar[120]; /* mensaje para mostrar en pantalla */ key_t clave; char* pname = argv[0]; int pid_pr = getpid(), childpid = 0; int qCompras, qVentas; PROTOCOLO envio, recepcion; COMPRA compra; TICKET resCompra; int clientNumber; char archivo[15]; /* contiene los productos a vender */ FILE* fp; /* archivo y estructura de compras */ char primeraLinea[80]; int cantidad, tiempo; if (!argc) { sprintf (mostrar, "Missing arguments"); write(fileno(stdout), mostrar, strlen(mostrar)); exit(1); } clientNumber = atoi(argv[1]); sprintf (mostrar, "Launched client %d\n", clientNumber); write(fileno(stdout), mostrar, strlen(mostrar)); sprintf(archivo, "cliente_%d.txt", clientNumber); if( ( fp = fopen(archivo,"r") ) == NULL) { sprintf (mostrar,"%s (%d): NO se puede abrir el archivo con las compras para el cliente %s\n", pname, pid_pr, archivo); write(fileno(stdout), mostrar, strlen(mostrar)); exit(1); } /* * abrir la cola compras */ clave = ftok(FTOK_DIR, Q_COMPRAS); if ((qCompras = msgget (clave, 0660)) == -1) { perror ("Cliente: error al hacer el get de la cola Compras "); exit (1); } /* * abrir la cola ventas */ clave = ftok(FTOK_DIR, Q_VENTAS); if ((qVentas = msgget (clave, 0660)) == -1) { perror ("Cliente: error al hacer el get de la cola Ventas "); exit (1); } envio.origen = clientNumber; fgets(primeraLinea,80,fp); /* Ignorar la primera linea. */ while(!feof(fp)){ /* descargar todo el archivo */ fscanf(fp,"%d %d", &cantidad, &compra.monto); sprintf (mostrar,"%s (%d): cantidad a comprar: %d dinero disponible %d\n", pname, pid_pr, cantidad, compra.monto); write(fileno(stdout), mostrar, strlen(mostrar)); // Solicitar vendedor envio.tipo = SOLICITAR_ATENCION; if (msgsnd(qCompras, &envio, sizeof(envio) - sizeof(long), 0) == -1){ perror ("Cliente: Error en el envio cola compras"); exit(2); } if (msgrcv(qVentas, &recepcion, sizeof(recepcion) - sizeof(long), clientNumber, 0) == -1){ if (errno == EINVAL || errno == EIDRM) { /* verifica si se destruyeron los IPC */ sprintf (mostrar,"%s (%d): TERMINA\n", pname, pid_pr); write(fileno(stdout), mostrar, strlen(mostrar)); exit(0); } else { perror ("Cliente: Error en la recepcion en cola envio "); exit (1); } } do { tiempo = rand() % 10; sleep(tiempo); sprintf (mostrar,"%s (%d): Empezando nueva compra, restan %d monto %d\n", pname, pid_pr, cantidad, compra.monto); write(fileno(stdout), mostrar, strlen(mostrar)); cantidad--; compra.mas = cantidad > 0; envio.tipo = recepcion.origen; memcpy (envio.mensaje, (char *)&compra, sizeof(compra)); if (msgsnd(qCompras, (PROTOCOLO*)&envio, sizeof(envio) - sizeof(long), 0) == -1){ perror ("Cliente: Error en el envio cola compras"); exit(2); } if (msgrcv(qVentas, (PROTOCOLO *)&recepcion, sizeof(recepcion) - sizeof(long), clientNumber, 0) == -1){ if (errno == EINVAL || errno == EIDRM) { /* verifica si se destruyeron los IPC */ sprintf (mostrar,"%s (%d): TERMINA\n", pname, pid_pr); write(fileno(stdout), mostrar, strlen(mostrar)); exit(0); } else { perror ("Cliente: Error en la recepcion en cola envio "); exit (1); } } memcpy ((char *)&resCompra, recepcion.mensaje, sizeof(resCompra)); if (resCompra.noHayMas) { sprintf (mostrar,"%s (%d): No hay mas tickets\n", pname, pid_pr); write(fileno(stdout), mostrar, strlen(mostrar)); exit(0); } if (resCompra.numero > 0) { sprintf (mostrar,"%s (%d): Adquiri el ticket: %d y me sobra %d\n", pname, pid_pr, resCompra.numero, resCompra.vuelto); write(fileno(stdout), mostrar, strlen(mostrar)); } else { sprintf (mostrar,"%s (%d): No pude adquirir el ticket\n", pname, pid_pr, resCompra.numero, resCompra.vuelto); write(fileno(stdout), mostrar, strlen(mostrar)); } compra.monto = resCompra.vuelto; } while(cantidad > 0 && resCompra.numero > 0); } fclose(fp); sprintf (mostrar,"%s (%d): Termine de comprar toda mi lista\n", pname, pid_pr, resCompra.numero, resCompra.vuelto); write(fileno(stdout), mostrar, strlen(mostrar)); return 0; }
int main(){ int id_msg, long_msg=sizeof(message)-sizeof(long); int i,j; int nbre_clients=0, nbre_clients2=0; int generation_id=2; produit p; message msg_recu, msg_envoi; //produit liste_produit[]={ // "carotte","pizza","navet","potimarron","raviolis","patate",".",".",".","."}; produit p1={0, "carotte", 5, 1.2}, p2={1, "pizza", 10, 3.5}, p3={2, "raviolis", 6, 2.5}, p4={3, "navet", 1, 1.7}, p5={4, "patate", 20, 0.2}; produit liste_produit[]={p1,p2,p3,p4,p5}; key_t key = ftok("./a.txt", 0); if(key==-1) perror("error ftok"); id_msg = msgget(key, IPC_CREAT|IPC_EXCL|0666); if(id_msg==-1) { //perror("msgget() - File existe deja !"); if(EEXIST == errno) // File de Message déjà existante { // Suppression de la file --> system("ipcs -q"); char buffer_key[50]; sprintf(buffer_key, "%d", key); char system_call[150]; strcpy(system_call, "ipcrm -Q "); strcat(system_call, buffer_key); //printf(system_call); printf("\n"); // Suppression system(system_call); // Re-création de la file id_msg = msgget(key, IPC_CREAT | IPC_EXCL | 0666); } } while(nbre_clients < 4){ if(msgrcv(id_msg, (void*)&msg_recu, long_msg, 1, 0)==-1) printf("erreur msgrcv\n"); else printf("Message recu\n"); if(nbre_clients2 < 3){ nbre_clients2++; switch(msg_recu.req_clt){ case -1: // affectation num client printf("Affectation num client\n"); nbre_clients++; msg_envoi.type=14; msg_envoi.id_clt=generation_id; // num msg_envoi.req_clt=0; msgsnd(id_msg, (void*)&msg_envoi, long_msg, 0); printf("Envoyé : %d\n\n",generation_id); generation_id++; break; case 3: // liste produit printf("Liste produit\n"); msg_envoi.type=msg_recu.id_clt; msg_envoi.id_clt=msg_recu.id_clt; // num msg_envoi.req_clt=0; for(j=0;j<MAX_ELT;j++) strcpy(msg_envoi.text[j], liste_produit[j].description); printf("Envoi de la liste\n\n"); msgsnd(id_msg, (void*)&msg_envoi, long_msg, 0); break; case 5: // détails pour un produit printf("Détail produit\n"); msg_envoi.type=msg_recu.id_clt; msg_envoi.id_clt=msg_recu.id_clt; // num msg_envoi.req_clt=0; p=liste_produit[msg_recu.id_produit-1]; char tmp[50]; sprintf(msg_envoi.text2,"Produit %s -> prix : %.1f€, %d en stock\n",p.description, p.prix, p.en_stock); printf("Envoi description du produit %s\n\n", p.description); msgsnd(id_msg, (void*)&msg_envoi, long_msg, 0); break; case 4: // ajouter n objets printf("Ajouter n objets\n"); msg_envoi.type=msg_recu.id_clt; msg_envoi.id_clt=msg_recu.id_clt; // num msg_envoi.req_clt=0; if(msg_recu.quantite>liste_produit[msg_recu.id_produit-1].en_stock) { msg_envoi.insuffisant = 1; printf("stock insuffisant pour le produit %s\n", liste_produit[msg_recu.id_produit-1].description); } else { msg_envoi.insuffisant = 0; liste_produit[msg_recu.id_produit-1].en_stock = liste_produit[msg_recu.id_produit-1].en_stock - msg_recu.quantite; } sprintf(msg_envoi.text2, "%s", liste_produit[msg_recu.id_produit-1].description); printf("%s, quantite restante : %d\n\n", liste_produit[msg_recu.id_produit-1].description, liste_produit[msg_recu.id_produit-1].en_stock); msgsnd(id_msg, (void*)&msg_envoi, long_msg, 0); break; case 6: //vider panier printf("Retour des objets du panier en stock\n"); for(j=0;j<5;j++) { liste_produit[j].en_stock = liste_produit[j].en_stock + msg_recu.retour_produit_quantite[j]; } } nbre_clients2--; } else printf("Sortie else\n"); } }
int main(int argc, char *argv[]) { int Rtnval; int Done; struct sigaction sig; DPT_RTN_T i; // // Set up our argument pointers for others to use // Argc = argc; Argv = argv; # if (defined(_DPT_SOLARIS) || defined(_DPT_ROOTONLY)) // Only root or sys are allowed to run dptutil. if ( ( getuid () != 0 ) && ( geteuid () != 0 ) && ( getuid () != 3 ) && ( geteuid () != 3 ) && ( getgid () != 0 ) && ( getegid () != 0 ) && ( getgid () != 3 ) && ( getegid () != 3 ) ) { printf ("You must be root to run this utility\n"); return (0); } # endif /* Parse The Command Line Parameters, And If An Error Exit */ if(ParseCommandLine(argc,argv)) { exit(ExitBadParameter); } #ifdef _SINIX_ADDON DEBUG_SETOUTPUT(est); if (DebugToFile) { DEBUG_BEGIN(5, "DPT Engine"); DEBUG_SETLEVEL(DebugToFile); } else DEBUG_OFF; SNI_set_compile_date(&engineSig); if (Signature) { printf("%s: V.%d.%c%c %.2d.%.2d.%d\n", engineSig.dsDescription, engineSig.dsVersion, engineSig.dsRevision, engineSig.dsSubRevision, engineSig.dsDay, engineSig.dsMonth, 1980 + engineSig.dsYear); exit(ExitGoodStatus); } #else DEBUG_SETOUTPUT(cerr); DEBUG_OFF; #endif /* Check To See If There Is Already An Engine Out There */ if (MkLock(NULL) == 1) { #ifndef _SINIX_ADDON if(Verbose) #endif printf( "\nThere Appears To Be Another Copy Of dpteng Already Running!\n"); exit(ExitDuplicateEngine); } /* If The Engine Cannot Be Opened, Print A Message And Exit */ i = DPT_StartEngine(); if(i != MSG_RTN_COMPLETED) { if(Verbose) { printf("\nStarting the Engine: "); if (i == ERR_OSD_OPEN_ENGINE) printf("Open HBA(s) "); else if (i == ERR_SEMAPHORE_ALLOC) printf("Alloc Semaphore "); else if (i == ERR_CONN_LIST_ALLOC) printf("Alloc Connection List "); else printf(" With Unknown Error %lx", (unsigned long)i); printf("Failed\n"); } RmLock(NULL); exit(ExitEngOpenFail); } /* Initialize The Signaling */ memset((void *)&sig,0,sizeof(sig)); #if defined ( _DPT_SCO ) || defined ( _DPT_AIX ) || defined( _DPT_BSDI ) || defined(_DPT_FREE_BSD ) || defined(_DPT_LINUX) sig.sa_handler = (void (*)(int))AlarmHandler; #elif defined ( _DPT_SOLARIS ) sig.sa_handler = (void (*)(int))AlarmHandler; /* M0001 - Added UnixWare Support */ #elif defined ( _DPT_UNIXWARE ) sig.sa_handler = (void (*)(int))AlarmHandler; /* M0001 - Added UnixWare DGUX */ #elif defined ( _DPT_DGUX ) sig.sa_handler = (void (*)_PROTO_ARGS((int)))AlarmHandler; #elif defined ( SNI_MIPS ) sig.sa_handler = (void (*)())AlarmHandler; #else #error Define this for your OS #endif #ifdef NEW_LOGGER #if defined(_DPT_SCO) || defined(_DPT_BSDI) || defined(_DPT_FREE_BSD) || defined(_DPT_LINUX) || defined (_DPT_SOLARIS) // ignore sighup, sigterm will come later after a few seconds signal(SIGHUP, (void (*) (int)) DptSignalIgnore); signal(SIGTERM, (void (*) (int)) DptSignalIgnore); signal(SIGCHLD, (void (*) (int)) DptSignalIgnore); #else #error Define me. These are shutdown signals to ignore so the SOC logger // can write its final heartbeat on a shutdown #endif #endif //#ifdef NEW_LOGGER /* If The Signaling Could Not Be Set Up, Print An Error And Exit */ if(sigaction(SIGALRM,&sig,0) == -1) { if(Verbose) printf("\nSignaling Could Not Be Set Up\n"); RmLock(NULL); exit(ExitSignalFail); } /* if no debug mode selected, start engine as daemon (like inetd) */ /* i.e. fork son proc and create new session id. - michiz */ if (!Verbose && !EataHex && !EataInfo && !DebugEngMsg) { int i; if ((i = fork()) != 0) { ChLock(NULL, i); exit(0); } setsid(); } #ifdef _SINIX_ADDON /* New option -stop to kill a hanged up engine */ if (ExitEngine) { int i; struct msqid_ds CtlBuf; MsqID = msgget(DPT_EngineKey, MSG_ALLRD | MSG_ALLWR); if(MsqID != -1) { msgctl(MsqID, IPC_STAT, &CtlBuf); // Stop engine only, if no dptmgr still running if ( CtlBuf.msg_lspid && CtlBuf.msg_lrpid && (getpgid(CtlBuf.msg_lspid) != -1) && (getpgid(CtlBuf.msg_lrpid) != -1)) printf("You must stop dptmgr first\n"); else { i = MessageDPTEngine(DPT_EngineKey, MsqID, ENGMSG_CLOSE, 2,1); if (i) msgctl(MsqID, IPC_RMID, &CtlBuf); if(Verbose) printf("dpteng successfully stopped\n"); } } RmLock(NULL); exit(ExitGoodStatus); } #endif /* Check To See If There Is Already An Engine Out There */ MsqID = CheckForEngine(DPT_EngineKey,1,2); if(MsqID != -1) { #ifndef _SINIX_ADDON if(Verbose) #endif printf( "\nThere Appears To Be Another Copy Of dpteng Already Running!\n"); RmLock(NULL); exit(ExitDuplicateEngine); } /* Get The Process ID To Use As The Unique Caller ID */ P_ID = getpid(); /* Try To Create The Unique Message Que Of This ID */ MsqID = msgget(DPT_EngineKey,IPC_CREAT | IPC_EXCL | MSG_ALLRD | MSG_ALLWR); /* If We Could Not Allocate The Message Que, Print A Message And Exit */ if(MsqID == -1) { if(Verbose) printf("\nThe Message Queue Could Not Be Allocated\n"); RmLock(NULL); exit(ExitMsqAllocFail); } /* Set Up The Function To Call When The Program Terminates Normally */ atexit(ProgramUnload); /* Loop Forever Waiting For A Header Message To Come In. Once A Header */ /* Message Is Received, We Will Attach To The Shared Memory Segment */ /* That Is Passed In The Header. This Memory Is The In And Out Buffers */ Done = 0; if(Verbose) printf("\ndpteng Is Ready.\n"); while(1) { // // At the top of the loop, we will pull off and process all turnaround messages on the queue since // they don't have to be sent down to the engine // while((Rtnval = (msgrcv(MsqID,(struct msgbuf *)&HdrBuff, MsgDataSize, DPT_TurnAroundKey,IPC_NOWAIT) != -1))) { Done = ProcessTurnAroundMessage(&HdrBuff); } // // If Done is set, there are no more clients, so let's // check for any messages in the queue before we exit. It // is possible that someone is trying to load and we don't // want to pull the rug out from under him // if(Done) { Rtnval = msgrcv(MsqID,(struct msgbuf *)&HdrBuff, MsgDataSize, -DPT_EngineKey,IPC_NOWAIT); // // If the call failed, were OUT-O-HERE // if(Rtnval == -1) { if(Verbose) { printf("\n : No Clients, Engine Unloads"); } break; } // // There was a message on the queue so continue processing // Done = 0; } // // Done is not set, so wait for a message to come in // else { while((Rtnval = (msgrcv(MsqID,(struct msgbuf *)&HdrBuff, MsgDataSize, -DPT_EngineKey,0) == -1))) { /* If The Message Failed, And The Reason Was Not An Interrupt, Exit */ if(errno != EINTR) break; } } /* If The Message Received OK Go Process It */ if(Rtnval == 0) { // // Check to make sure this guy is still out there before processing the message // if not, throw away the message // if(kill(HdrBuff.callerID,0) != 0) { if(Verbose) { printf("\n : Message received for PID %ld : no process found, discarding", HdrBuff.callerID); } continue; } /* If This Is A Turnarround Message, Process it */ if((HdrBuff.engineTag == HdrBuff.callerID)&& (HdrBuff.engineTag == HdrBuff.targetTag)) { Done = ProcessTurnAroundMessage(&HdrBuff); continue; } /* Attach To The Shared Memory */ toEng_P = (uCHAR *)shmat((int)HdrBuff.BufferID,0,0); /* Make Sure That We Could Attach */ if((long)toEng_P != -1) { fromEng_P = toEng_P + HdrBuff.FromEngBuffOffset; /* M0000 : New Verbose Statements */ if(Verbose) { FormatTimeString(TimeString,time(0)); printf("\nEngine Calls : %s DPT_CallEngine",TimeString); printf( "\n EngTag = %lx, Event = %lx, Target = %lx", (unsigned long)HdrBuff.engineTag, (unsigned long)HdrBuff.engEvent, (unsigned long)HdrBuff.targetTag); printf( "\n Offset = %lx fromEng_P = %lx toEng_P = %lx", HdrBuff.FromEngBuffOffset, (unsigned long)fromEng_P, (unsigned long)toEng_P); /*#else "\n EngTag = %x, Event = %x, Target = %x", HdrBuff.engineTag,HdrBuff.engEvent,HdrBuff.targetTag); #endif */ fflush(stdout); } /* All Went Well With The Receive, So Call The Engine */ HdrBuff.result = DPT_Engine( HdrBuff.engineTag, HdrBuff.engEvent, HdrBuff.targetTag, fromEng_P,toEng_P, HdrBuff.timeOut); // // Detach from the memory segment // shmdt((char *)toEng_P); // // Check to make sure this guy is still out there before returning the message // if not, throw away the message // if(kill(HdrBuff.callerID,0) != 0) { if(Verbose) { printf("\n : Returning message for PID %ld : no process found, discarding", HdrBuff.callerID); } continue; } /* Set Up The Proper Message Type In The Buffer Headers */ HdrBuff.MsgID = HdrBuff.callerID; HdrBuff.callerID = DPT_EngineKey; Rtnval = msgsnd(MsqID,(struct msgbuf *)&HdrBuff,MsgDataSize,0); /* If We Had An Error Sending, Print A Message And Exit */ if(Rtnval == -1) { if(Verbose) { FormatTimeString(TimeString,time(0)); printf( "\n%s Error Sending A Message In The Engine : %d\n", TimeString,errno); fflush(stdout); } RmLock(NULL); exit(ExitMsgSendFail); } } /* else printf("\nError Trying To Attach To The Memory"); */ } /* If We Had An Error Receiving, Print A Message And Exit */ else { if(Verbose) { FormatTimeString(TimeString,time(0)); printf( "\n%s Error Receiving A Message In The Engine : %d\n", TimeString,errno); fflush(stdout); } RmLock(NULL); exit(ExitMsgReceiveFail); } } } //main(int argc, char *argv[])
int RcvMsgQ() { int infolen; int bAskQuit = 0; msgbuf send_buf; msgbuf receive_buf; if((infolen=msgrcv(m_msqid_to_d,&receive_buf,MAX_IPC_MSG_BUF,0,0))<0) { if (errno == EINTR) { return 0; } else { myprintf("TP_INIT:msgrcv err\n"); return -1; } } else { //printf("msgrcv ok\n"); int bSendResp = 1; if (IPC_CLIENT_MSG_Q_ID == receive_buf.mtype) { int* pInt; pInt=(int*)(&receive_buf.mtext[0]); myprintf("TP_INIT:IPC_CLIENT_MSG_Q_ID\n"); m_msqid_from_d = *pInt; myprintf("%d\n",m_msqid_from_d); bSendResp = 0; } else if (IPC_START_AUTO_DET == receive_buf.mtype) { myprintf("TP_INIT:IPC_START_AUTO_DET\n"); // delete timer disable_polling(); // wait timer function exit wait_polling_stop(); send_buf.mtype=IPC_START_AUTO_DET; strcpy(send_buf.mtext,"Start Done"); } else if (IPC_ADD_PVC == receive_buf.mtype) { unsigned short idx; unsigned short vlan_id; unsigned short vpi; unsigned short vci; unsigned short encap; unsigned short mode; unsigned short* pWord; pWord=(unsigned short*)(&receive_buf.mtext[0]); int add_ret; myprintf("TP_INIT:IPC_ADD_PVC\n"); idx = *pWord++; vlan_id = *pWord++; vpi = *pWord++; vci = *pWord++; encap = *pWord++; mode = *pWord; myprintf("ADDPVC:%d %d %d %d %d %d\n",idx,vlan_id,vpi,vci,encap,mode); add_ret = AddPvc(idx,vlan_id,vpi,vci,encap,mode); send_buf.mtype=IPC_ADD_PVC; if (add_ret == 0) strcpy(send_buf.mtext,"OK"); else strcpy(send_buf.mtext,"FAIL"); } else if (IPC_DEL_ALL_PVC == receive_buf.mtype) { int del_ret; myprintf("TP_INIT:IPC_DEL_ALL_PVC\n"); del_ret = DelAllPvc(); send_buf.mtype=IPC_DEL_ALL_PVC; if (del_ret == 0) strcpy(send_buf.mtext,"OK"); else strcpy(send_buf.mtext,"FAIL"); } /* Paul add 2012/8/7 */ else if (IPC_ATE_ADSL_RESTORE_DEFAULT == receive_buf.mtype) { int rst_ret; myprintf("TP_INIT:IPC_ATE_ADSL_RESTORE_DEFAULT\n"); rst_ret = RestoreDefault(); send_buf.mtype=IPC_ATE_ADSL_RESTORE_DEFAULT; if (rst_ret == 0) strcpy(send_buf.mtext,"OK"); else strcpy(send_buf.mtext,"FAIL"); } //Ren.B else if (IPC_ATE_ADSL_GET_BITS_PER_CARRIER == receive_buf.mtype) { int rst_ret; myprintf("TP_INIT:IPC_ATE_ADSL_GET_BITS_PER_CARRIER\n"); rst_ret = getBitsPerCarrier(); send_buf.mtype=IPC_ATE_ADSL_GET_BITS_PER_CARRIER; if (rst_ret == 0) strcpy(send_buf.mtext,"OK"); else strcpy(send_buf.mtext,"FAIL"); } else if (IPC_ATE_ADSL1_GET_SNR == receive_buf.mtype) { int rst_ret; myprintf("TP_INIT:IPC_ATE_ADSL1_GET_SNR\n"); rst_ret = getSNR_ADSL1(); send_buf.mtype=IPC_ATE_ADSL1_GET_SNR; if (rst_ret == 0) strcpy(send_buf.mtext,"OK"); else strcpy(send_buf.mtext,"FAIL"); } else if (IPC_ATE_ADSL2_PLUS_GET_SNR == receive_buf.mtype) { int rst_ret; myprintf("TP_INIT:IPC_ATE_ADSL2_PLUS_GET_SNR\n"); rst_ret = getSNR_ADSL2_PLUS(); send_buf.mtype=IPC_ATE_ADSL2_PLUS_GET_SNR; if (rst_ret == 0) strcpy(send_buf.mtext,"OK"); else strcpy(send_buf.mtext,"FAIL"); } //Ren.E else if (IPC_LINK_STATE == receive_buf.mtype) { char LinkSts[30]; myprintf("TP_INIT:IPC_LINK_STATE\n"); GetLinkSts(LinkSts, sizeof(LinkSts)); send_buf.mtype=IPC_LINK_STATE; if (!strcmp(LinkSts,"wait for initializing")) { // nvram could not allow space character strcpymax(send_buf.mtext,"wait_for_init",MAX_IPC_MSG_BUF); } else { strcpymax(send_buf.mtext,LinkSts,MAX_IPC_MSG_BUF); } } else if (IPC_STOP_AUTO_DET == receive_buf.mtype) { myprintf("TP_INIT:IPC_STOP_AUTO_DET\n"); send_buf.mtype=IPC_STOP_AUTO_DET; strcpy(send_buf.mtext,"Stop Done"); enable_polling(); } else if (IPC_ATE_ADSL_SHOW == receive_buf.mtype) { myprintf("TP_INIT:IPC_ATE_ADSL_SHOW\n"); UpdateAllAdslSts(0,1); send_buf.mtype=IPC_ATE_ADSL_SHOW; strcpy(send_buf.mtext,"AteSetDone"); } else if (IPC_ATE_ADSL_QUIT_DRV == receive_buf.mtype) { myprintf("TP_INIT:IPC_ATE_ADSL_QUIT_DRV\n"); bAskQuit = 1; send_buf.mtype=IPC_ATE_ADSL_QUIT_DRV; strcpy(send_buf.mtext,"AteSetDone"); } else if (IPC_ATE_ADSL_DISP_PVC == receive_buf.mtype) { myprintf("TP_INIT:IPC_ATE_ADSL_DISP_PVC\n"); DispAllPvc(); send_buf.mtype=IPC_ATE_ADSL_DISP_PVC; strcpy(send_buf.mtext,"AteSetDone"); } else if (IPC_ATE_SET_ADSL_MODE == receive_buf.mtype) { unsigned short mode; unsigned short type; unsigned short* pWord; pWord=(unsigned short*)(&receive_buf.mtext[0]); int set_ret_mode, set_ret_type; myprintf("TP_INIT:IPC_ATE_SET_ADSL_MODE\n"); mode = *pWord++; type = *pWord++; myprintf("SET MODE:%d %d\n",mode,type); set_ret_mode = SetAdslMode(mode,1); set_ret_type = SetAdslType(type,1); send_buf.mtype=IPC_ATE_SET_ADSL_MODE; if (set_ret_mode == 0 && set_ret_type) strcpy(send_buf.mtext,"OK"); else strcpy(send_buf.mtext,"FAIL"); } else if (IPC_RELOAD_PVC == receive_buf.mtype) { int del_ret; myprintf("TP_INIT:IPC_RELOAD_PVC\n"); del_ret = DelAllPvc(); reload_pvc(); send_buf.mtype=IPC_RELOAD_PVC; strcpy(send_buf.mtext,"OK"); } if (bSendResp) { if(msgsnd(m_msqid_from_d,&send_buf,MAX_IPC_MSG_BUF,0)<0) { myprintf("msgsnd fail\n"); return -1; } } } if (bAskQuit == 1) return 1; return 0; }
int recv_msg(int id, t_msg* msg, t_idmsg type, int flag) { return (msgrcv(id, msg, sizeof(*msg), type, flag)); }
int main (int argc, char *argv[]) // integrate [sin(x), {x, 0, 10}] = 1.83907152908 { struct timeval t1, t2; double elapsedTime; gettimeofday(&t1, NULL); int a = 0, b = 10; int Ninter = 0, Nprocs = 0; long double localsum = 0, width = 0; int msqid = get_msqid(); register int iproc = 0, pid = 0; if (argc == 3) { Ninter = atoi (argv[1]); Nprocs = atoi (argv[2]); } else { ERROR ("Usage: newton %%d intervals %%d processes"); } if (Nprocs == -1) { if (msgctl (msqid, IPC_RMID, 0) == -1) { perror ("msgctl failed"); exit (1); } return 0; } size_t msglen = sizeof (my_msg); width = (double) (b - a)/Ninter; for (iproc = 0; iproc < Nprocs; iproc++) { pid = fork(); if (pid < 0) { perror ("Error in fork\n"); exit(1); } if (pid == 0) { iproc++; break; } } if (pid == 0) // computer { register int i = 0; register double cur_a = 0, cur_b = 0; localsum = 0; for (i = iproc; i <= Ninter; i += Nprocs) { cur_a = a + width*(i - 1); cur_b = cur_a + width; localsum += compute_interval (cur_a, cur_b); } my_msg msglocalsum = {0, 0}; msglocalsum.localsum = localsum; msglocalsum.iproc = iproc; // fprintf(stderr, "%d \t %g \t %g \t %Lg\n", iproc, cur_a, cur_b, localsum); if (msgsnd (msqid, &msglocalsum, msglen, 0) == -1) { perror ("msgsnd failed"); exit (1); } } else // collector { my_msg msg = {0, 0}; register int i = 0; register long double sum = 0; for (i = 0; i < Nprocs; i++) { if (msgrcv (msqid, &msg, msglen, 0, 0) == -1) { perror ("msgrcv failed"); exit (1); } sum += msg.localsum; } wait (NULL); gettimeofday(&t2, NULL); elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0; elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0; // printf("integrate [sin(x), {x, 0, 10}] = %Lg (estimated 1.83907152908)\n", sum); // printf("Time elapsed: %g\n", elapsedTime); printf("%g\n", elapsedTime); } return 0; }
MsgEventQ_t *MsgOpen(MsgEventQType_t type, char *name, int namelen) { MsgEventQ_t *ret = NULL; msg_t msg; MsgQInitReqEvent_t initreq; MsgQInitGntEvent_t initgnt; int r; switch(type) { #ifdef HAVE_SYSV_MSG case MsgEventQType_msgq: { int msqid = atoi(name); msg.msgq.mtype = CLIENT_RESOURCE_MANAGER; //the recipient of this message initreq.type = MsgEventQInitReq; // we want a handle memcpy(msg.msgq.event_data, &initreq, sizeof(MsgQInitReqEvent_t)); if(msgsnd(msqid, (void *)&msg, sizeof(MsgQInitReqEvent_t), 0) == -1) { perror("MsgOpen, snd"); return NULL; } else { if(msgrcv(msqid, (void *)&msg, sizeof(MsgEvent_t), CLIENT_UNINITIALIZED, 0) == -1) { perror("MsgOpen, rcv"); return NULL; } else { ret = (MsgEventQ_t *)malloc(sizeof(MsgEventQ_t)); ret->msgq.type = MsgEventQType_msgq; ret->msgq.msqid = msqid; // which msq to wait for messages on memcpy(&initgnt, msg.msgq.event_data, sizeof(MsgQInitGntEvent_t)); ret->msgq.mtype = initgnt.newclientid; // mtype to wait for } } } break; #endif case MsgEventQType_socket: { int sd; struct sockaddr_un unix_addr = { 0 }; struct sockaddr_un tmp_addr = { 0 }; struct sockaddr_un from_addr = { 0 }; int from_addr_len; int n; static unsigned int ser = 0; long int tmp_clientid; if((sd = socket(PF_UNIX, SOCK_DGRAM, 0)) == -1) { perror("socket"); return NULL; } tmp_addr.sun_family = AF_UNIX; //try 10 times then fail for(n=0; n<10; n++) { //create a name for the socket tmp_clientid = getpid()*10+ser; ser = (ser+1)%10; snprintf(tmp_addr.sun_path, sizeof(tmp_addr.sun_path), "%s/%ld", name, tmp_clientid); if(bind(sd, (struct sockaddr *)&tmp_addr, sizeof(tmp_addr)) == -1) { perror("bind()"); //return NULL; } else { break; } } if(n==10) { return NULL; } initreq.type = MsgEventQInitReq; // we want a handle initreq.client = tmp_clientid; memcpy(msg.socket.event_data, &initreq, sizeof(MsgQInitReqEvent_t)); unix_addr.sun_family = AF_UNIX; if(strlen(name) >= sizeof(unix_addr.sun_path)) { return NULL; } snprintf(unix_addr.sun_path, sizeof(unix_addr.sun_path), "%s/%ld", name, CLIENT_RESOURCE_MANAGER); #if 0 if(connect(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) == -1) { perror("connect"); return NULL; } #endif //send init request if((r = sendto(sd, &msg, sizeof(MsgQInitReqEvent_t), 0, (struct sockaddr *)&unix_addr, sizeof(unix_addr))) == -1) { perror("MsgOpen, sendto"); return NULL; } //wait for response from_addr_len = sizeof(from_addr); if((r = recvfrom(sd, &msg, sizeof(msg), 0, (struct sockaddr *)&from_addr, &from_addr_len)) == -1) { perror("MsgOpen, recvfrom"); return NULL; } ret = (MsgEventQ_t *)malloc(sizeof(MsgEventQ_t)); ret->socket.type = MsgEventQType_socket; //ret->socket.server_addr = unix_addr; // resource manager addr ret->socket.server_addr.sun_family = AF_UNIX; snprintf(ret->socket.server_addr.sun_path, sizeof(ret->socket.server_addr.sun_path), "%s", name); memcpy(&initgnt, msg.socket.event_data, sizeof(MsgQInitGntEvent_t)); ret->socket.client_addr.sun_family = AF_UNIX; snprintf(ret->socket.client_addr.sun_path, sizeof(ret->socket.client_addr.sun_path), "%s/%d", name, (int)initgnt.newclientid); ret->socket.clientid = initgnt.newclientid; if(unlink(tmp_addr.sun_path) == -1) { perror("msgopen, unlink"); fprintf(stderr, "'%s'\n", tmp_addr.sun_path); } close(sd); if((sd = socket(PF_UNIX, SOCK_DGRAM, 0)) == -1) { perror("socket"); return NULL; } if(bind(sd, (struct sockaddr *)&ret->socket.client_addr, sizeof(ret->socket.client_addr)) == -1) { perror("msgopen bind()"); fprintf(stderr, "'%s' %d\n", ret->socket.client_addr.sun_path, sizeof(ret->socket.client_addr)); return NULL; } ret->socket.sd = sd; } break; case MsgEventQType_pipe: break; } return ret; }
MSG * retirer(long type, int id_file){ MSG *m = (MSG*)malloc(sizeof(MSG)); /* Bloque l'appelant jusqu'à ce que le message soit du bon type*/ msgrcv(id_file, m, sizeof(MSG), type, 0); return m; }
static int MsgNextEvent_internal(MsgEventQ_t *q, MsgEvent_t *event_return, int interruptible) { msg_t msg; switch(q->type) { #ifdef HAVE_SYSV_MSG case MsgEventQType_msgq: while(1) { if(msgrcv(q->msgq.msqid, (void *)&msg, sizeof(MsgEvent_t), q->msgq.mtype, 0) == -1) { switch(errno) { case EINTR: // syscall interrupted if(!interruptible) { continue; } break; default: perror("MsgNextEvent"); break; } return -1; } else { memcpy(event_return, msg.msgq.event_data, sizeof(MsgEvent_t)); return 0; } } break; #endif case MsgEventQType_socket: while(1) { struct sockaddr_un from_addr; int from_addr_len; int rlen; from_addr_len = sizeof(from_addr); if((rlen = recvfrom(q->socket.sd, (void *)&msg, sizeof(MsgEvent_t), 0, (struct sockaddr *)&from_addr, &from_addr_len)) == -1) { switch(errno) { case EINTR: // syscall interrupted if(!interruptible) { continue; } break; default: perror("MsgNextEvent"); break; } return -1; } else { memcpy(event_return, msg.socket.event_data, rlen); #ifdef XDEBUG fprintf(stderr, "MsgNextEvent: pid: %d got %s (%d B) from %d\n", getpid(), MsgEventType_str[event_return->any.type], rlen, event_return->any.client); #endif return 0; } } break; case MsgEventQType_pipe: fprintf(stderr, "NOT IMPLEMENTED pipe\n"); break; } return -1; }
int main(int argc, char **argv) { int msgqid; // Test basic operation. // create a message queue. msgqid = msgget(IPC_PRIVATE, IPC_CREAT|IPC_EXCL|0600); //staptest// msgget (IPC_PRIVATE, IPC_CREAT|IPC_EXCL|0600) = NNNN // create a message to send msg.mtype = 1; strcpy(msg.mtext, "a text msg...\n"); // send the message to queue msgsnd(msgqid, &msg, sizeof(msg), IPC_NOWAIT); //staptest// msgsnd (NNNN, XXXX, NNNN, IPC_NOWAIT) = NNNN // read the message from queue msgrcv(msgqid, &msg, sizeof(msg), 0, 0); //staptest// msgrcv (NNNN, XXXX, NNNN, 0, 0x0) = NNNN // remove the queue msgctl(msgqid, IPC_RMID, NULL); //staptest// msgctl (NNNN, [[[[IPC_64|]]]]?IPC_RMID, 0x0) = 0 // Range checking. msgqid = msgget((key_t)-1, IPC_CREAT|IPC_EXCL|0600); //staptest// msgget (-1, IPC_CREAT|IPC_EXCL|0600) = NNNN msgsnd(-1, &msg, sizeof(msg), 0); //staptest// msgsnd (-1, XXXX, NNNN, 0x0) = NNNN msgsnd(msgqid, (void *)-1, sizeof(msg), 0); #ifdef __s390__ //staptest// msgsnd (NNNN, 0x[7]?[f]+, NNNN, 0x0) = NNNN #else //staptest// msgsnd (NNNN, 0x[f]+, NNNN, 0x0) = NNNN #endif msgsnd(msgqid, &msg, (size_t)-1, 0); #if __WORDSIZE == 64 //staptest// msgsnd (NNNN, XXXX, 18446744073709551615, 0x0) = NNNN #else //staptest// msgsnd (NNNN, XXXX, 4294967295, 0x0) = NNNN #endif msgsnd(msgqid, &msg, sizeof(msg), -1); //staptest// msgsnd (NNNN, XXXX, NNNN, [[[[MSG!!!!IPC]]]]_[^ ]+|XXXX) = NNNN msgrcv(-1, &msg, sizeof(msg), 0, 0); //staptest// msgrcv (-1, XXXX, NNNN, 0, 0x0) = NNNN msgrcv(msgqid, (void *)-1, sizeof(msg), 0, 0); #ifdef __s390__ //staptest// msgrcv (NNNN, 0x[7]?[f]+, NNNN, 0, 0x0) = NNNN #else //staptest// msgrcv (NNNN, 0x[f]+, NNNN, 0, 0x0) = NNNN #endif msgrcv(msgqid, &msg, (size_t)-1, 0, 0); #if __WORDSIZE == 64 //staptest// msgrcv (NNNN, XXXX, 18446744073709551615, 0, 0x0) = NNNN #else //staptest// msgrcv (NNNN, XXXX, 4294967295, 0, 0x0) = NNNN #endif msgrcv(msgqid, &msg, sizeof(msg), -1, IPC_NOWAIT); //staptest// msgrcv (NNNN, XXXX, NNNN, -1, IPC_NOWAIT) = NNNN msgrcv(msgqid, &msg, sizeof(msg), 0, -1); //staptest// msgrcv (NNNN, XXXX, NNNN, 0, [[[[MSG!!!!IPC]]]]_[^ ]+|XXXX) = NNNN msgctl(msgqid, IPC_RMID, NULL); //staptest// msgctl (NNNN, [[[[IPC_64|]]]]?IPC_RMID, 0x0) = NNNN msgqid = msgget(IPC_PRIVATE, -1); //staptest// msgget (IPC_PRIVATE, IPC_[^ ]+|XXXX|0777) = NNNN msgctl(msgqid, IPC_RMID, NULL); //staptest// msgctl (NNNN, [[[[IPC_64|]]]]?IPC_RMID, 0x0) = NNNN msgctl(msgqid, -1, NULL); //staptest// msgctl (NNNN, [[[[IPC_64|]]]]?XXXX, 0x0) = NNNN msgctl(msgqid, IPC_RMID, (struct msqid_ds *)-1); #ifdef __s390__ //staptest// msgctl (NNNN, [[[[IPC_64|]]]]?IPC_RMID, 0x[7]?[f]+) = NNNN #else //staptest// msgctl (NNNN, [[[[IPC_64|]]]]?IPC_RMID, 0x[f]+) = NNNN #endif return 0; }
int MsgCheckEvent(MsgEventQ_t *q, MsgEvent_t *event_return) { msg_t msg; #ifdef XDEBUG fprintf(stderr, "MsgCheckEvent: pid: %d\n", getpid()); #endif #ifdef SOCKIPC switch(q->type) { #ifdef HAVE_SYSV_MSG case MsgEventQType_msgq: while (1) { if(msgrcv(q->msgq.msqid, (void *)&msg, sizeof(MsgEvent_t), q->msgq.mtype, IPC_NOWAIT) == -1) { switch(errno) { #ifdef ENOMSG case ENOMSG: #endif case EAGAIN: break; case EINTR: // interrupted by system call/signal, try again continue; break; default: perror("MsgNextEvent"); break; } return -1; } else { memcpy(event_return, msg.msgq.event_data, sizeof(MsgEvent_t)); return 0; } } break; #endif case MsgEventQType_socket: #ifdef HAVE_POLL while (1) { struct sockaddr_un from_addr; int from_addr_len; struct pollfd fds[1]; int r; int rlen; fds[0].fd = q->socket.sd; fds[0].events = POLLIN; from_addr_len = sizeof(from_addr); r = poll(fds, 1, 0); if(r > 0) { if(fds[0].revents & POLLIN) { if((rlen = recvfrom(q->socket.sd, (void *)&msg, sizeof(MsgEvent_t), 0, (struct sockaddr *)&from_addr, &from_addr_len)) == -1) { switch(errno) { case EAGAIN: break; case EINTR: // interrupted by system call/signal, try again continue; break; default: perror("MsgNextEvent"); break; } return -1; } else { memcpy(event_return, msg.socket.event_data, rlen); #ifdef XDEBUG fprintf(stderr, "MsgCheckEvent: pid: %d got %s (%d B), from: %d\n", getpid(), MsgEventType_str[event_return->any.type], rlen, event_return->any.client); #endif return 0; } } } else if(r == -1) { switch(errno) { case EAGAIN: case EINTR: continue; break; default: perror("MsgNextEvent, poll"); return -1; break; } } else { return -1; } } #else //HAVE_POLL while (1) { struct sockaddr_un from_addr; int from_addr_len; fd_set rfds; struct timeval tv; int r; int rlen; int nfds; FD_ZERO(&rfds); FD_SET(q->socket.sd, &rfds); nfds = q->socket.sd + 1; tv.tv_sec = 0; tv.tv_usec = 0; from_addr_len = sizeof(from_addr); r = select(nfds, &rfds, NULL, NULL, &tv); if(r > 0) { if(FD_ISSET(q->socket.sd, &rfds)) { if((rlen = recvfrom(q->socket.sd, (void *)&msg, sizeof(MsgEvent_t), 0, (struct sockaddr *)&from_addr, &from_addr_len)) == -1) { switch(errno) { case EAGAIN: break; case EINTR: // interrupted by system call/signal, try again continue; break; default: perror("MsgNextEvent"); break; } return -1; } else { memcpy(event_return, msg.socket.event_data, rlen); #ifdef XDEBUG fprintf(stderr, "MsgCheckEvent: pid: %d got %s (%d B), from: %d\n", getpid(), MsgEventType_str[event_return->any.type], rlen, event_return->any.client); #endif return 0; } } } else if(r == -1) { switch(errno) { case EINTR: continue; break; default: perror("MsgNextEvent, select"); return -1; break; } } else { return -1; } } #endif //HAVE_POLL break; case MsgEventQType_pipe: break; } #else while (1) { if(msgrcv(q->msqid, (void *)&msg, sizeof(MsgEvent_t), q->mtype, IPC_NOWAIT) == -1) { switch(errno) { #ifdef ENOMSG case ENOMSG: #endif case EAGAIN: break; case EINTR: // interrupted by system call/signal, try again continue; break; default: perror("MsgNextEvent"); break; } return -1; } else { memcpy(event_return, msg.event_data, sizeof(MsgEvent_t)); return 0; } } #endif return -1; }
int main(int argc, char const *argv[]) { int up_msgqid, down_msgqid, rv_bytes, nClients = 0, i, flag; char dtype[TYPE_SIZE], data[DATA_SIZE], chatID[ID_SIZE], sd_time_buf[TIME_SIZE]; pid_t pid; time_t sd_time; struct mymsgbuf rc_message; struct mymsgbuf sd_message; struct msqid_ds buf; struct ele mapping[MAX_CLIENTS], element; up_msgqid = msgget(UP, IPC_CREAT | 0666); down_msgqid = msgget(DOWN, IPC_CREAT | 0666); if (up_msgqid == -1 || down_msgqid == -1){ perror("Unable to create message Queue..."); exit(1); } while(1) { rv_bytes = msgrcv(up_msgqid, &rc_message, MSG_SIZE, 0, 0); strcpy(dtype, rc_message.dtype); if (!strcmp(dtype, "NEW")) { strcpy(element.chatID, rc_message.chatID); element.pid = rc_message.mtype; mapping[nClients++] = element; printf("Client PID = %d, ChatID = %s has just logged in...\n", element.pid, element.chatID); printf("%d Clients Online\n", nClients); strcpy(data, ""); for (i = 0; i < nClients; ++i) { strcat(data, mapping[i].chatID); strcat(data, ","); } strcpy(sd_message.dtype, "LIST"); strcpy(sd_message.data, data); for (i = 0; i < nClients; ++i) { sd_message.mtype = mapping[i].pid; flag = msgsnd(down_msgqid, &sd_message, MSG_SIZE, IPC_NOWAIT); } printf("Updated Client List sent to all Clients...\n\n"); } else if (!strcmp(dtype, "MSG")) { strcpy(data, rc_message.data); pid = rc_message.mtype; for (i = 0; i < nClients; ++i) { if(mapping[i].pid == pid) { strcpy(chatID, mapping[i].chatID); break; } } printf("A message received from PID = %d, ChatID = %s\n", pid, chatID); msgctl(up_msgqid, IPC_STAT, &buf); printf("No. of Messages in UP-Queue : %lu\n", buf.msg_qnum); sd_time = buf.msg_stime; strftime(sd_time_buf, TIME_SIZE, "%H:%M:%S", localtime(&sd_time)); strcpy(sd_message.sd_time_buf, sd_time_buf); strcpy(sd_message.chatID, chatID); strcpy(chatID, rc_message.chatID); for (i = 0; i < nClients; ++i) { if(!strcmp(mapping[i].chatID, chatID)){ pid = mapping[i].pid; break; } } sd_message.mtype = pid; strcpy(sd_message.dtype,"MSG"); strcpy(sd_message.data, rc_message.data); msgsnd(down_msgqid, &sd_message, MSG_SIZE, IPC_NOWAIT); printf("A message sent to PID = %d, ChatID = %s\n", pid, rc_message.chatID); msgctl(down_msgqid, IPC_STAT, &buf); printf("No. of Messages in DOWN-Queue : %lu\n\n", buf.msg_qnum); } } return 0; }
//server thread, one per client void *serverThread(void *data){ int candidateQID; //msg queue ID of candidateQID (for CHAT) int clientQID; //msg queue ID of private server-client queue CLLNode *clientCLL, *threadCLLNext; //pointer to next candidate in client thread JOINMsg *jMsgPtr = data, jMsg; CLIENTMsg cMsg, canMsg, tempMsg; dStruct *dBuffer; int retval; pthread_t pingThread; //create private semaphore between server thread and client 'sem+PID', w/init value = 0 char semname[MAXNAMELEN]; sem_t *tSemPtr; jMsg.PID = jMsgPtr->PID; jMsg.AAIdx = jMsgPtr->AAIdx; strcpy(jMsg.mname, jMsgPtr->mname); strcpy(jMsg.minfo, jMsgPtr->minfo); dBuffer = initClient(&jMsg); clientQID = dBuffer->clQID; clientCLL = dBuffer->clNodePtr; threadCLLNext = Head; //initialize current candidate to Head of CLL sprintf(semname, "/tSem%d", jMsg.PID); umask(0x0000); tSemPtr = sem_open(semname, O_CREAT, S_IRUSR|S_IWUSR|S_IROTH|S_IWOTH, 0); if (tSemPtr == SEM_FAILED){ perror("sem_open"); } printClientsFwd(); setMsg(ACK, &cMsg, threadCLLNext); //send ACK message to client if( msgsnd(clientQID, &cMsg, sizeof(CLIENTMsg)-sizeof(long), 0) == -1){ fprintf(stderr, "Server: cannot send ACK message to client PID: %d\n", cMsg.PID); perror("msgsnd"); } printf("ACK message sent to client\n"); //-----semwait(sem+PID) here //if( sem_wait(tSemPtr) < 0){ perror("sem_wait"); } sleep(1); //create (sub)thread to "PING" client to see if connection is still good. Set timeout of about 1 ms. /* retval = pthread_create(&pingThread, NULL, ping, (void*)jMsgPtr); if( retval ){ fprintf(stderr, "\n Server: error(%d): cannot create connection pinger ping()\n", retval); perror("pthread_create"); } */ cMsg.mtype = PASS; while (cMsg.mtype != QUIT) { /* serverThread listens for commands from client*/ if (clientCount == 1){ //only one (self) client logged on, override command type in message cMsg.mtype = NIL; cMsg.PID = -1; cMsg.status = NOTLIKED; strcpy(cMsg.mname, threadCLLNext->name); strcpy(cMsg.minfo, threadCLLNext->info); } printf("client %d mtype is %ld\n", clientCLL->PID, cMsg.mtype); switch (cMsg.mtype){ case PASS: printf("PASS command received\n"); threadCLLNext = threadCLLNext->Next; //check linked list for the next candidate while (threadCLLNext->PID == -1 || threadCLLNext->PID == jMsg.PID) threadCLLNext = threadCLLNext->Next; //advance ptr to next if Head or same as client //determine status of next candidate and set status bits setStatus(&cMsg, clientCLL, threadCLLNext); printf("In PASS, cMsg.status=%d, cMsg.PID=%d, cMsg.mname=%s,\n cMsg.minfo=%s\n", cMsg.status, cMsg.PID, cMsg.mname, cMsg.minfo); setMsg(OK, &cMsg, threadCLLNext); msgsnd(clientQID, &cMsg, sizeof(CLIENTMsg)-sizeof(long), 0); //send info to client //-----semwait(sem+PID) here //if( sem_wait(tSemPtr) < 0){ perror("sem_wait"); } break; case ENDCHAT: //ENDCHAT command can come from either client - procedure similar to PASS, can combine threadCLLNext = threadCLLNext->Next; //check linked list for the next candidate while (threadCLLNext->PID == -1 || threadCLLNext->PID == jMsg.PID) threadCLLNext = threadCLLNext->Next; //advance ptr to next if Head or same as client //determine status of next candidate and set status bits setStatus(&cMsg, clientCLL, threadCLLNext); setMsg(OK, &cMsg, threadCLLNext); msgsnd(clientQID, &cMsg, sizeof(CLIENTMsg)-sizeof(long), 0); //send info to client //-----semwait(sem+PID) here //if( sem_wait(tSemPtr) < 0){ perror("sem_wait"); } break; case LIKE: printf("LIKE command received\n"); //update client's Like Matrix against current candidate to like. LikeMatrix[clientCLL->AssignArrIdx][threadCLLNext->AssignArrIdx] = 'L'; //---rest same as PASS threadCLLNext = threadCLLNext->Next; //check linked list for the next candidate while (threadCLLNext->PID == -1 || threadCLLNext->PID == jMsg.PID) threadCLLNext = threadCLLNext->Next; //advance ptr to next if Head or same as client //determine status of next candidate and set status bits setStatus(&cMsg, clientCLL, threadCLLNext); setMsg(OK, &cMsg, threadCLLNext); msgsnd(clientQID, &cMsg, sizeof(CLIENTMsg)-sizeof(long), 0); //send info to client //-----semwait(sem+PID) here //if( sem_wait(tSemPtr) < 0){ perror("sem_wait"); } break; case CHAT: //CHAT command originates from client (single starting point) msgsnd(clientQID, &cMsg, sizeof(CLIENTMsg)-sizeof(long), 0);//relays back CHAT message to originator client //-----semwait(sem+PID) here //if( sem_wait(tSemPtr) < 0){ perror("sem_wait"); } //determine candidateQID of current candidate (threadCLLNext) to be able to send message to that client MQ candidateQID = initClientQueue("ftokfile.txt", threadCLLNext->PID); printf("CHAT command received, clientQID is %d, candidateQID is %d\n", clientQID, candidateQID); canMsg.status = 0x0003; //status is MATCHED setMsg(CHATCAN, &canMsg, clientCLL); //send canMsg to current candidate to CHATCAN msgsnd(candidateQID, &canMsg, sizeof(CLIENTMsg)-sizeof(long), 0); //client should send ENDCHAT command if client ends chat //-----NONONONO semwait(sem+PID) here break; case CHATCAN: //to be able to synch properly, this recipient server thread must read (ahead) the next message from its client in the MQ and store the command. //Commands can be PASS, LIKE, QUIT, CHAT, ENDCHAT, (or another CHATCAN) //After the CHATCAN msg is sent to the client, the stored command is processed. //Alternatively, the command from the client can be discarded. This will simplify the processing by quite a bit... In this way, the message synch is maintained if (msgrcv(clientQID, &tempMsg, sizeof(CLIENTMsg)-sizeof(long), 0, 0) == -1) perror("msgrcv"); //As you can see, handling this case can be quite complex!!!!! msgsnd(clientQID, &cMsg, sizeof(CLIENTMsg)-sizeof(long), 0);//relays back CHAT message to candidate client //-----semwait(sem+PID) here, since received an extra msg from chat originator candidate //if( sem_wait(tSemPtr) < 0){ perror("sem_wait"); } break; case NIL: printf("NIL command received\n"); msgsnd(clientQID, &cMsg, sizeof(CLIENTMsg)-sizeof(long), 0); //-----semwait(sem+PID) here //if( sem_wait(tSemPtr) < 0){ perror("sem_wait"); } threadCLLNext = threadCLLNext->Next; //check linked list for the next candidate if (threadCLLNext->PID == -1) threadCLLNext = threadCLLNext->Next; //advance ptr to next if Head break; case QUIT: //same as DISCONNECTED:, removeClient() is called after exit from while() loop case DISCONNECTED: break; default: fprintf(stderr, "Server: error - invalid command from client %d\n", cMsg.PID); //should disconnect client and close server thread (to recover and save server's state) break; }//END switch() if (msgrcv(clientQID, &cMsg, sizeof(CLIENTMsg)-sizeof(long), 0, 0) == -1) { perror("msgrcv"); } //-----sempost(sem+PID) here //if( sem_post(tSemPtr) < 0){ perror("sem_post"); } }//END while (cMsg.mtype != QUIT) loop //thread closing procedures (QUIT command received from client) removeClient(clientQID, clientCLL); //pthread_join(pingThread, NULL); //send UNJOIN message to Join MQ so server can free up space (pthread_join) in thread array, and decrease the client count. jMsg.mtype = UNJOIN; printf("UNJOIN sent to server parent. Client PID is %d\n", jMsg.PID); //jMsgPtr->PID = same; msgsnd(joinQID, &jMsg, sizeof(JOINMsg)-sizeof(long), 0); pthread_exit(NULL); }
int no_recover_and_ioctl() { int rc; struct ctx my_ctx; struct ctx *p_ctx = &my_ctx; //__u64 flags; pthread_t thread; __u64 chunk = 0x1; __u64 stride= 0x1; pthread_t ioThreadId; #ifdef _AIX //these are unused on Linux int msgid; struct mymsgbuf msg_buf; #endif do_io_thread_arg_t ioThreadData; do_io_thread_arg_t * p_ioThreadData=&ioThreadData; char * noIOP = getenv("NO_IO"); pid = getpid(); printf("%d:no_recover_and_ioctl process created...\n",pid); rc = ctx_init(p_ctx); CHECK_RC(rc, "Context init failed"); rc = create_resource(p_ctx, chunk *(p_ctx->chunk_size), DK_UVF_ALL_PATHS, LUN_VIRTUAL); CHECK_RC(rc, "create LUN_VIRTUAL failed"); if ( noIOP == NULL ) { //thread to handle AFU interrupt & events pthread_create(&thread, NULL, ctx_rrq_rx, p_ctx); p_ioThreadData->p_ctx=p_ctx; p_ioThreadData->stride=stride; p_ioThreadData->loopCount=100; rc = pthread_create(&ioThreadId,NULL, do_io_thread, (void *)p_ioThreadData); CHECK_RC(rc, "do_io_thread() pthread_create failed"); } #ifdef _AIX rc = do_eeh(p_ctx); #else rc = do_poll_eeh(p_ctx); #endif if ( noIOP == NULL ) { pthread_join(ioThreadId, NULL); } if ( noIOP == NULL ) pthread_cancel(thread); #ifdef _AIX msgid = msgget(key, IPC_CREAT | 0666); if (msgid < 0 ) { fprintf(stderr, "%d: msgget() failed before msgsnd()\n", pid); return -1; } if (msgrcv(msgid, &msg_buf, 2, 2, 0) < 0) { fprintf(stderr, "%d: msgrcv failed with errno %d\n", pid, errno); return -1; } sleep(1); rc = create_resource(p_ctx, p_ctx->chunk_size, DK_UVF_ALL_PATHS, LUN_VIRTUAL); rc |= vlun_resize(p_ctx, 2*p_ctx->chunk_size); rc |= close_res(p_ctx); rc |= ctx_close(p_ctx); #else // For the lost context, we will create another new. rc = ctx_init(p_ctx); CHECK_RC(rc, "Context init failed"); //thread to handle AFU interrupt & events pthread_create(&thread, NULL, ctx_rrq_rx, p_ctx); rc = create_resource(p_ctx, chunk *(p_ctx->chunk_size), DK_UVF_ALL_PATHS, LUN_VIRTUAL); pthread_cancel(thread); #endif return rc; }
void make_queue() { int msqid, fid, sid; key_t key; struct mymsgbuf { long mtype; int mat_part[MAXLEN+1]; } mybuf; fid = open_file(); sid = make_sem(); if (num_cl == 1) sem_a(sid); // Generation of IPC key if((key = ftok(KEYFILE,0)) < 0) { printf("Can't generate key\n"); exit(-1); } //Get access for key if((msqid = msgget(key, 0666 | IPC_CREAT)) < 0) { printf("Can't get msqid\n"); exit(-1); } int flag=1; // Client start receive and send massages while(flag) { //rsv massage if ( (msgrcv(msqid, &mybuf,(MAXLEN+1)*sizeof(int), num_cl + cln_num, 0)) < 0) { printf("can't receive message in CLIENT!\n"); exit(-1); } write_log("CLN RSV\n", sid, fid); //analyse of massage if(mybuf.mat_part[0] == STOPWORK) flag = 0; else { //last massage in queue delite all ipc if(mybuf.mat_part[0] == BY) { if ((msgrcv(msqid, &mybuf,(MAXLEN+1)*sizeof(int),3*cln_num, 0)) < 0) { printf("can't receive message in LAST CLIENT!\n"); exit(-1); } if (semctl(sid, 0, IPC_RMID, 0)<0) { printf("ERROR in delite semophore\n"); exit(-1); } if( msgctl(msqid, IPC_RMID, NULL) < 0) { printf("ERROR in delite queue\n"); exit(-1); } if( close(fid) < 0) { printf("ERROR in close file\n"); exit(-1); } } //if it's not last massage we just close client else { mybuf.mtype = num_cl; mybuf.mat_part[0] = WORKDONE; bsort(mybuf.mat_part); if( (msgsnd(msqid, &mybuf, (MAXLEN+1)*sizeof(int), 0)) < 0) { printf("can't send message in CLIENT!\n"); exit(-1); } write_log("CLN SND\n", sid, fid); } } } write_log("I'm FINISH\n", sid, fid); }
void msgq_rcvr(msg_t *message) { msgrcv(msg_q_id, message, MSG_SIZE, 1, 0); }
int main(int argc, char* argv[]){ static int msg_q_ID; static bool actuator_running; static char devName [16]; static int randNum, threshold ,msg_recv_status; static long int curr_PID; static long int recv_msg_type; static char str_buffer [128]; static dev_data_t send_data_1; static ack_data_t received_data_from_ctrl; actuator_running = true; curr_PID = getpid(); recv_msg_type = curr_PID*10; printf("The current PID is: %li\n-------------------------\n", curr_PID ); send_data_1.msg_type = curr_PID; printf("The Message Type is: %li\n", send_data_1.msg_type ); //Catches if less than 2 arguments are supplied if(argc<1){ fprintf(stderr, "ERROR: Not enough arguments supplied\n\tRequired Parameters for Actuator: Device Name \n\n"); exit(EXIT_FAILURE); } strcpy(devName,"ACT: "); strcat(devName,argv[1]); //Creates a message queue with a key msg_q_ID = msgget((key_t)MSG_Q_KEY, 0666); //If message queue creation fails if (msg_q_ID == -1) { fprintf(stderr, "ERROR: Message Queue creation failed. Err #%d\n",errno); exit(EXIT_FAILURE); } printf("Message Queue Used: %d\n",msg_q_ID); //Structuring initial message send_data_1.msg_data.pid = curr_PID; send_data_1.msg_data.status = STATUS_INIT; send_data_1.msg_data.trshVal = 0; send_data_1.msg_data.currVal = 0; strcpy(send_data_1.msg_data.devType,devName); printf("Sending Initial message --> PID: %d\tDevice name: %s\tDevice Status: %d\n", send_data_1.msg_data.pid,send_data_1.msg_data.devType,send_data_1.msg_data.status); if(msgsnd(msg_q_ID, (void *)&send_data_1, BUFFER_SIZE, 0) == -1){ fprintf(stderr, "ERROR: Message not sent to Controller. Err # %d\n", errno); exit(EXIT_FAILURE); } if (msgrcv(msg_q_ID, (void*)&received_data_from_ctrl,BUFFER_SIZE, recv_msg_type , 0 ) == -1) { fprintf(stderr, "ERROR: Message not received. Err # %d\n", errno); exit(EXIT_FAILURE); } printf("Message from Controller: %s\n------------------------\n",received_data_from_ctrl.ack_msg); if( strncmp(received_data_from_ctrl.ack_msg, "ACK", 3) == -1){ fprintf(stderr, "ERROR: Did not receive ACK Message. Err #%d\n",errno); exit(EXIT_FAILURE); } send_data_1.msg_data.status = STATUS_NORMAL; printf("Running Normal Behaviour\n------------------------\n"); //Periodically checks the message queue if a message is received while(actuator_running){ if (msgrcv(msg_q_ID, (void*)&received_data_from_ctrl,sizeof(ack_data_t), (long int) recv_msg_type , 0 )== -1) { fprintf(stderr, "ERROR: Did not receive Message from Controller. Err #%d\n",errno); exit(EXIT_FAILURE); } if(strncmp(received_data_from_ctrl.ack_msg,"STOP",4)==0){ actuator_running = false; break; } else{ //Prints command printf("Command: %s %s.\n",argv[1],received_data_from_ctrl.ack_msg); //Send Acknowledgement message back to the controller strcpy(received_data_from_ctrl.ack_msg, "ACK"); received_data_from_ctrl.msg_type = curr_PID; if(msgsnd(msg_q_ID, (void *)&received_data_from_ctrl, BUFFER_SIZE, 0) == -1){ fprintf(stderr, "ERROR: Message not sent to Controller. Err # %d\n", errno); exit(EXIT_FAILURE); } } sleep(0.5); } printf("Exit program\n"); return 0; }