int main() { int i; /*liczniki*/ int j; int tmp; struct task *shmTasks; struct sembuf semUnblock[2]; struct sembuf semBlock[2]; struct task newTask; /* semafory: * 0 -- blokada konsumentów * 1 -- blokada gwarantująca atomiczność operacji na wspólnej pamięci * 2 -- blokada producentów*/ srand((uint)time(0)); if(memKey == -1) memKey = ftok(".",811); tmp = atexit(myatexit); memId = shmget(memKey, (size_t)shmSize, IPC_CREAT | IPC_EXCL | 0755); /*try create*/ if(memId == -1) { if(errno != EEXIST) { myerror("Błąd shmget(3p)!",1); } memId = shmget(memKey, prodAndKonsCnt, 0); /*try get*/ if(memId == -1) { myerror("Błąd shmget(3p)",2); } } else { rimuwEshaemAwterEgzit = 1; } mem = shmat(memId, 0, 0); if(mem == (void*)-1) { myerror("Błąd shmat(3p)!",3); } else if(rimuwEshaemAwterEgzit) { ((int*)mem)[0] = 0; /*jeśli utworzyliśmy -- wyzerujmy licznik klientów i producentów*/ ((int*)mem)[1] = 0; } if(semKey == -1) semKey = ftok(".",812); semId = semget(semKey, semCnt, IPC_CREAT | IPC_EXCL | 0755); if(semId == -1) { if(errno != EEXIST) myerror("Błąd semget(3p)!",4); semId = semget(semKey, semCnt, 0); if(semId == -1) myerror("Błąd semget(3p)!",5); } else { rimuwEseemAwterEgzit = 1; for(i=0;i<2;++i) if(semctl(semId, i, SETVAL, i) == -1) /*blokuj sem0 (konsumentów), odblokuj sem1 (licznik)*/ myerror("Błąd semctl(3p)!",6); if(semctl(semId, 2, SETVAL, prodAndKonsCnt) == -1) /*odblokuj sem2 (producentów)*/ myerror("Błąd semctl(3p)!",7); } imem = (int*)mem; shmTasks = (struct task*)((int*)mem+2*sizeof(int)); prodCurrCnt = imem; semBlock[0].sem_num = semaforAtom; /*blokowanie producentów (teraz klienci) + gwarancja atomiczności*/ semBlock[1].sem_num = semaforProducent; semBlock[0].sem_op = semBlock[1].sem_op = -1; semUnblock[0].sem_num = semaforKonsument; /*odblokowywanie klientów (bo teraz oni rządzą) + zdjęcie gwarancji atomiczności*/ semUnblock[1].sem_num = semaforAtom; semUnblock[0].sem_op = semUnblock[1].sem_op = 1; semBlock[0].sem_flg = semUnblock[0].sem_flg = \ semBlock[1].sem_flg = semUnblock[1].sem_flg = 0; for(;;) { /*producentujemy*/ newTask.op = rand()%(operacjaIloczyn-operacjaSuma+1)+operacjaSuma; for(i=0; i<matrixSize; ++i) { for(j=0; j<matrixSize; ++j) { newTask.a[i][j] = rand()%10; newTask.b[i][j] = rand()%10; } } #if DEBUGMODE printf("\n------------------------------\nUmieszczam task:\n\top=%d\n\ta= (",newTask.op); printTaskDetails(&newTask); printf("\n\tDodawanie... "); #endif tmp = semop(semId, semBlock, 2); /*blokujemy producentów + atomiczność*/ if(tmp == -1) myerror("Błąd semop(3p)!",8); #if DEBUGMODE printf(" [xx]"); #endif #if DEBUGMODE printf(" [%d]",imem[0]); #endif shmTasks[imem[0]] = newTask; #if DEBUGMODE printf(" [OK]"); #endif tmp = semop(semId, semUnblock, 2); /*odblokowujemy producentów + rozatomiczność*/ imem[0] = (imem[0]+1)%prodAndKonsCnt; if(tmp == -1) myerror("Błąd semop(3p)!",9); #if DEBUGMODE printf(" [++]\n"); #else printf("Umieściłem zadanie w pamięci\n"); #endif } return 0; /*never called*/ }
int invopen(INVCONTROL *invcntl, char *invname, char *invpost, int stat) { int read_index; if ((invcntl->invfile = vpfopen(invname, ((stat == 0) ? "rb" : "r+b"))) == NULL) { /* If db created without '-f', but now invoked with '-f cscope.out', * we need to check for 'cscope.in.out', rather than 'cscope.out.in': * I.e, hack around our own violation of the inverse db naming convention */ if (!invflipname(invname, INVNAME2, INVNAME)) { if ((invcntl->invfile = vpfopen(invname, ((stat == 0) ? "rb" : "r+b")))) goto openedinvname; invflipname(invname, INVNAME, INVNAME2); /* change back for err msg */ } /* more silliness: if you create the db with '-f cscope', then try to open * it without '-f cscope', you'll fail unless we check for 'cscope.out.in' * here. */ else if (!invflipname(invname, INVNAME, INVNAME2)) { if ((invcntl->invfile = vpfopen(invname, ((stat == 0) ? "rb" : "r+b")))) goto openedinvname; invflipname(invname, INVNAME2, INVNAME); /* change back for err msg */ } invcannotopen(invname); return(-1); } openedinvname: if (fread(&invcntl->param, sizeof(invcntl->param), 1, invcntl->invfile) == 0) { fprintf(stderr, "%s: empty inverted file\n", argv0); goto closeinv; } if (invcntl->param.version != FMTVERSION) { fprintf(stderr, "%s: cannot read old index format; use -U option to force database to rebuild\n", argv0); goto closeinv; } assert(invcntl->param.sizeblk == sizeof(t_logicalblk)); if (stat == 0 && invcntl->param.filestat == INVALONE) { fprintf(stderr, "%s: inverted file is locked\n", argv0); goto closeinv; } if ((invcntl->postfile = vpfopen(invpost, ((stat == 0) ? "rb" : "r+b"))) == NULL) { /* exact same naming convention hacks as above for invname */ if (!invflipname(invpost, INVPOST2, INVPOST)) { if ((invcntl->postfile = vpfopen(invpost, ((stat == 0) ? "rb" : "r+b")))) goto openedinvpost; invflipname(invpost, INVPOST, INVPOST2); /* change back for err msg */ } else if (!invflipname(invpost, INVPOST, INVPOST2)) { if ((invcntl->postfile = vpfopen(invpost,((stat == 0)?"rb":"r+b")))) goto openedinvpost; invflipname(invpost, INVPOST2, INVPOST); /* change back for err msg */ } invcannotopen(invpost); goto closeinv; } openedinvpost: /* allocate core for a logical block */ if ((invcntl->logblk = malloc((unsigned) invcntl->param.sizeblk)) == NULL) { invcannotalloc((unsigned) invcntl->param.sizeblk); goto closeboth; } /* allocate for and read in superfinger */ read_index = 1; invcntl->iindex = NULL; #if SHARE if (invcntl->param.share == 1) { key_t shm_key; struct shmid_ds shm_buf; int shm_id; /* see if the shared segment exists */ shm_key = ftok(invname, 2); shm_id = shmget(shm_key, 0, 0); /* Failure simply means (hopefully) that segment doesn't exists */ if (shm_id == -1) { /* Have to give general write permission due to AMdahl not having protected segments */ shm_id = shmget(shm_key, invcntl->param.supsize + sizeof(long), IPC_CREAT | 0666); if (shm_id == -1) perror("Could not create shared memory segment"); } else read_index = 0; if (shm_id != -1) { invcntl->iindex = shmat(shm_id, 0, ((read_index) ? 0 : SHM_RDONLY)); if (invcntl->iindex == (char *)ERR) { fprintf(stderr, "%s: shared memory link failed\n", argv0); invcntl->iindex = NULL; read_index = 1; } } } #endif if (invcntl->iindex == NULL) /* FIXME HBB: magic number alert (4) */ invcntl->iindex = malloc((unsigned) invcntl->param.supsize + 4 *sizeof(long)); if (invcntl->iindex == NULL) { invcannotalloc((unsigned) invcntl->param.supsize); free(invcntl->logblk); goto closeboth; } if (read_index) { fseek(invcntl->invfile, invcntl->param.startbyte, SEEK_SET); fread(invcntl->iindex, (int) invcntl->param.supsize, 1, invcntl->invfile); } invcntl->numblk = -1; if (boolready() == -1) { closeboth: fclose(invcntl->postfile); closeinv: fclose(invcntl->invfile); return(-1); } /* write back out the control block if anything changed */ invcntl->param.filestat = stat; if (stat > invcntl->param.filestat ) { rewind(invcntl->invfile); fwrite(&invcntl->param, sizeof(invcntl->param), 1, invcntl->invfile); } return(1); }
int main() { int *shared_array; int id; char pathname[] = "part1.c"; key_t key; key = ftok(pathname, 0); if ((id = shmget(key,(3*max*max+2)*sizeof(int),0666|IPC_CREAT|IPC_EXCL)) < 0) { id = shmget(key, (3*max*max+2)*sizeof(int), 0); } shared_array = (int*)shmat(id, NULL, 0); pid_t process; process = fork(); /* Reading */ if (process ==0) { freopen("in.txt", "r", stdin); scanf("%d %d\n", &shared_array[0], &shared_array[1]); int n = shared_array[0]; int m = shared_array[1]; for (i=2;i<2*n*m+2;i++) { scanf("%d", &shared_array[i]); } return 0; } waitpid(process, NULL, 0); /* Summing */ process = fork(); if (process == 0) { int n = shared_array[0]; int m = shared_array[1]; for (i=0;i<n;i++) { for (j=0;j<m;j++) { shared_array[2+2*n*m+i*m+j] = shared_array[2+m*i+j] + shared_array[2+m*n+m*i+j]; } } return 0; } waitpid(process, NULL, 0); /* Printing */ process = fork(); if (process == 0) { int n = shared_array[0]; int m = shared_array[1]; for (i=0; i < n; i++) { for (j=0; j < m; j++) { printf("%d ",shared_array[2+2*n*m+i*m+j]); } printf("\n"); } return 0; } waitpid(process, NULL, 0); return 0; }
int main (int argc, char **argv){ int i; key_t shmkey; int shmid; sem_t *semFive; pid_t pid; int *p; int leftOrRight; int flag = 0; int myP; unsigned int n = 23; unsigned int valueFive = 5; srand(time(NULL)); // shared memory shmkey = ftok ("/dev/null", 5); printf ("shmkey for p = %d\n", shmkey); shmid = shmget (shmkey, sizeof (int), 0644 | IPC_CREAT); if (shmid < 0){ perror ("shmget\n"); exit (1); } p = (int *) shmat (shmid, NULL, 0); *p = 0; semFive = sem_open("tSem", O_CREAT | O_EXCL, 0644, valueFive); sem_unlink("tSem"); printf ("Semaphores initialized.\n\n"); for (i = 0; i < n; i++){ pid = fork (); leftOrRight = rand()%2; if((i == 0) && (pid == 0)) *p = leftOrRight; if (pid < 0) printf ("Fork error.\n"); else if (pid == 0) break; } //parent process if (pid != 0){ // wait for all of your kids while (pid = waitpid (-1, NULL, 0)){ if (errno == ECHILD) break; } printf ("\nParent: All of orangutans crossed through the rope.\n"); shmdt (p); shmctl (shmid, IPC_RMID, 0); // destroy semaphore sem_destroy(semFive); exit (0); } // kids process else{ while(leftOrRight != *p) { } sem_wait(semFive); myP = *p; printf (" Orangutan(%d) is on the rope.\n", i); // time, when orangutan is on the rope sleep (2); // 0 - orangutan crossed from left side of rope to right // 1 - orangutan crossed from right side of rope to left printf("Orangutan(%d) crossed - left[0] or right[1] side: %d\n" ,i, leftOrRight); sem_post(semFive); sem_getvalue(semFive, &flag); if(flag == valueFive) *p = leftOrRight^1; exit (0); } }
// brcm static void config_save() { /*start of HG553 2008.03.29 V100R001C02B010 AU8D00340 by yepeng */ FILE *fp; char path[128]=""; char cmd[128]=""; char fileName[128]=""; #ifdef VDF_OPTION char dfpath[128] = ""; #endif char temps[32]; int DataFlag = 0; int iRetryTimes =0; if (strlen(session_path) > 0) sprintf(path, "%s/%s/%s", _PATH_WAN_DIR, session_path, _PATH_IP); file_save(path, local_ip, FALSE); if (strlen(session_path) > 0) sprintf(path, "%s/%s/%s", _PATH_WAN_DIR, session_path, _PATH_MASK); /*start of HG553V100R001C02B019 2008.07.05 AU8D00754 */ if(strlen(subnet_ip)) { file_save(path, subnet_ip, FALSE); } /*end of HG553V100R001C02B019 2008.07.05 AU8D00754 */ sprintf(cmd, "mkdir -p %s", _PATH_SYS_DIR); system(cmd); /*start of 根据vdf 要求业务自动切换需要切换dns by s53329 at 20080115 file_save(_PATH_RESOLV, dns_ip, TRUE); end of 根据vdf 要求业务自动切换需要切换dns by s53329 at 20080115*/ if (strlen(dns_ip)) { fp = fopen("/var/HspaDataStatus","r"); if(fp) { fgets(temps,32,fp); if(strchr(temps,'1')) { DataFlag = 1; } else { DataFlag = 0; } fclose(fp); } if (0 == DataFlag) { //ADSL模式时如果已有则不写入 file_save("/var/fyi/sys/dynamicdns", dns_ip, TRUE); } else { //HSPA模式时则会覆盖 file_save("/var/fyi/sys/dynamicdns", dns_ip, FALSE); sprintf(cmd,"echo 0 >/var/HspaDataStatus"); system(cmd); } /*start of 清空dns 配置信息,避免dns接口与路由接口不同 by s53329 at 20080507 file_save(_PATH_RESOLV, dns_ip, FALSE); end of 清空dns 配置信息,避免dns接口与路由接口不同 by s53329 at 20080507*/ } if (strlen(router_ip)) { if (0 == DataFlag) { //ADSL模式时如果已有则不写入 file_save(_PATH_GW, router_ip, TRUE); } else { //HSPA模式时则会覆盖 file_save(_PATH_GW, router_ip, FALSE); } } /*end of HG553 2008.03.29 V100R001C02B010 AU8D00340 by yepeng */ /*start of 增加保存各接口默认网关功能by s53329 at 20071220*/ #ifdef VDF_OPTION if (strlen(session_path) > 0) { if(strlen(dns_ip)> 0) { sprintf(path, "%s/%s", _PATH_WAN_ROOT, session_path); sprintf(cmd, "mkdir -p %s", path); system(cmd); sprintf(path, "%s/%s/dns", _PATH_WAN_ROOT, session_path); file_save(path, dns_ip, FALSE); } } if (strlen(session_path) > 0) { if(strlen(option_121) > 0) { //处理option121, 如果option121中带有静态路由,该函数会修改router_ip的值 file_save_route(); } if(strlen(router_ip)> 0) { sprintf(cmd, "mkdir -p %s/%s", _PATH_WAN_ROOT, session_path); system(cmd); sprintf(dfpath, "%s/%s/%s", _PATH_WAN_ROOT, session_path, _PATH_DEFAULT_ROUTE); file_save(dfpath, router_ip, FALSE); } } #else if (strlen(session_path) > 0) { sprintf(path, "%s/%s", _PATH_INTERFACE_GW, session_path); sprintf(cmd, "mkdir -p %s", path); system(cmd); sprintf(path, "%s/%s/%s", _PATH_INTERFACE_GW, session_path, _PATH_GATAWAY); file_save(path, router_ip, FALSE); } if (strlen(session_path) > 0) { sprintf(path, "%s/%s", _PATH_INTERFACE_GW, session_path); sprintf(cmd, "mkdir -p %s", path); system(cmd); sprintf(path, "%s/%s/dns", _PATH_INTERFACE_GW, session_path); file_save(path, dns_ip, FALSE); } #endif /*end of 增加保存各接口默认网关功能by s53329 at 20071220*/ /*START ADD:Jaffen for pvc dns setting A36D03768*/ /*start of 增加wan接口对应的dns功能 by s53329 at 20080217*/ //#ifdef SINGAPORE_LOGIN /*start of 解决只能发主dns 地址解析,从地址解析失败问题 by s53329 at 20080220 if(strlen(dns_ip) > 0) { char dns[256]; sprintf(path, "%s/%s/%s", _PATH_WAN_DIR, session_path, _PATH_DNS); dns[0] = 0xa; dns[1] = '\0'; file_save(path,dns,0); if( strstr(dns_ip,"\n") != NULL ) { memset(dns,0,sizeof(dns)); if((strstr(dns_ip,"\n") - dns_ip-1) < sizeof(dns)) { strncpy(dns, dns_ip, strstr(dns_ip,"\n") - dns_ip-1); dns[sizeof(dns)-1] = '\0'; } if(strlen(strstr(dns_ip,"\n")+1) < sizeof(dns)) { strcat(dns,strstr(dns_ip,"\n")+1); } file_save(path, dns, 0); } else { if(strlen(dns_ip) < sizeof(dns)) { strcpy(dns,dns_ip); file_save(path, dns, 0); } } } */ if(strlen(dns_ip) > 0) { char dns[256]; sprintf(path, "%s/%s/%s", _PATH_WAN_DIR, session_path, _PATH_DNS); if(strlen(dns_ip) < sizeof(dns)) { strcpy(dns,dns_ip); file_save(path, dns, 0); } } /*end of 解决只能发主dns 地址解析,从地址解析失败问题 by s53329 at 20080220 */ //#endif /*END ADD:Jaffen for pvc dns setting A36D03768*/ /*end of 增加wan接口对应的dns功能 by s53329 at 20080217*/ //printf("router_ip:%s\r\n",router_ip); /*START MODIFY: liujianfeng 37298 for [A36D03489] at 2007-03-16*/ /*start of 修改 策略路由丢失问题 by s53329 at 20080218*/ if(strlen(router_ip)) { /*end of 修改 策略路由丢失问题 by s53329 at 20080218*/ sprintf(fileName,"gw_%s",client_config.Interface); printf("\nclient_config.Interface=%s\n",fileName); (void)tmpfile_writevalue(fileName, router_ip); /*start of 修改 策略路由丢失问题 by s53329 at 20080218*/ } /*end of 修改 策略路由丢失问题 by s53329 at 20080218*/ /*END MODIFY: liujianfeng 37298 for [A36D03489] at 2007-03-16*/ /*start of WAN <3.4.5桥使能dhcp, option17> porting by s60000658 20060505*/ (void)tmpfile_writevalue("RootPath", root_path); /*end of WAN <3.4.5桥使能dhcp, option17> porting by s60000658 20060505*/ /* start of maintain dhcp server地址通过dhcp获取 by liuzhijie 00028714 2006年7月7日" */ FILE *fs; int pid; char line[16]; key_t key; int msgid; struct { long mtype; char mtext[128]; } msg; /* end of maintain dhcp server地址通过dhcp获取 by liuzhijie 00028714 2006年7月7日" */ /*w44771 add for more dhcp option, begin, 2006-6-29*/ if (strlen (option_timezone) > 0 ) { (void)tmpfile_writevalue("timezone", option_timezone); } if (strlen (option_logsvr1) > 0 ) { (void)tmpfile_writevalue("logsvr1", option_logsvr1); if (strlen (option_logsvr2) > 0 ) { (void)tmpfile_writevalue("logsvr2", option_logsvr2); } /* start of maintain syslog server地址通过dhcp获取 by liuzhijie 00028714 2006年7月10日 */ #ifdef SUPPORT_SYSLOG_AUTOCONF key = ftok(CFM_MSG_PATH, CFM_MSG_SEED); msgid = msgget(key, IPC_CREAT | 0666); if (-1 == msgid) { printf("Error: get message queue in dhcp process failed."); } else { msg.mtype = LOGSRV_DHCP_TYPE; iRetryTimes =0; while (-1 == msgsnd(msgid, &msg, 0, IPC_NOWAIT)) { iRetryTimes++; if (10 <= iRetryTimes) { perror("ntpsvr"); break; } usleep(100000); } } #endif /* end of maintain syslog server地址通过dhcp获取 by liuzhijie 00028714 2006年7月10日 */ } if (strlen (option_logsvr_string) > 0 ) { (void)tmpfile_writevalue("logsvr_string", option_logsvr_string); /* start of maintain syslog server地址通过dhcp获取 by liuzhijie 00028714 2006年7月10日 */ #ifdef SUPPORT_SYSLOG_AUTOCONF key = ftok(CFM_MSG_PATH, CFM_MSG_SEED); msgid = msgget(key, IPC_CREAT | 0666); if (-1 == msgid) { printf("Error: get message queue in dhcp process failed."); } else { msg.mtype = LOGSRV_DHCP_TYPE; iRetryTimes = 0; while (-1 == msgsnd(msgid, &msg, 0, IPC_NOWAIT)) { iRetryTimes++; if (10 <= iRetryTimes) { perror("ntpsvr"); break; } usleep(100000); } } #endif /* end of maintain syslog server地址通过dhcp获取 by liuzhijie 00028714 2006年7月10日 */ } if (strlen (option_tftpsvr1) > 0 ) { (void)tmpfile_writevalue("tftpsvr1", option_tftpsvr1); if (strlen (option_tftpsvr2) > 0 ) { (void)tmpfile_writevalue("tftpsvr2", option_tftpsvr2); } } if (strlen (option_tftp_string) > 0 ) { (void)tmpfile_writevalue("tftp_string", option_tftp_string); } if (strlen (option_hostname_string) > 0 ) { (void)tmpfile_writevalue("hostname", option_hostname_string); } if (strlen (option_domain_string) > 0 ) { (void)tmpfile_writevalue("domain", option_domain_string); } if (strlen (option_ntpsvr1) > 0 ) { (void)tmpfile_writevalue("ntpsvr1", option_ntpsvr1); if (strlen (option_ntpsvr2) > 0 ) { (void)tmpfile_writevalue("ntpsvr2", option_ntpsvr2); } /* start of maintain sntp server地址通过dhcp获取 by liuzhijie 00028714 2006年7月7日" */ #ifdef SUPPORT_SNTP_AUTOCONF key = ftok(CFM_MSG_PATH, CFM_MSG_SEED); msgid = msgget(key, IPC_CREAT | 0666); if (-1 == msgid) { printf("Error: get message queue in dhcp process failed."); } else { msg.mtype = SNTPSRV_DHCP_TYPE; iRetryTimes = 0; while (-1 == msgsnd(msgid, &msg, 0, IPC_NOWAIT)) { iRetryTimes++; if (10 <= iRetryTimes) { perror("ntpsvr"); break; } usleep(100000); } } #endif /* end of maintain sntp server地址通过dhcp获取 by liuzhijie 00028714 2006年7月7日" */ } if (strlen (option_ntpsvr_string) > 0 ) { (void)tmpfile_writevalue("ntpsvr_string", option_ntpsvr_string); /* start of maintain sntp server地址通过dhcp获取 by liuzhijie 00028714 2006年7月7日" */ #ifdef SUPPORT_SNTP_AUTOCONF key = ftok(CFM_MSG_PATH, CFM_MSG_SEED); msgid = msgget(key, IPC_CREAT | 0666); if (-1 == msgid) { printf("Error: get message queue in dhcp process failed."); } else { msg.mtype = SNTPSRV_DHCP_TYPE; iRetryTimes = 0; while (-1 == msgsnd(msgid, &msg, 0, IPC_NOWAIT)) { iRetryTimes++; if (10 <= iRetryTimes) { perror("ntpsvr"); break; } usleep(100000); } } #endif /* end of maintain sntp server地址通过dhcp获取 by liuzhijie 00028714 2006年7月7日" */ } if (strlen (option_tftp_string) > 0 ) { (void)tmpfile_writevalue("tftp_string", option_tftp_string); } if (strlen (option_bootfile_string) > 0 ) { (void)tmpfile_writevalue("bootfile", option_bootfile_string); } /*w44771 add for more dhcp option, begin, 2006-6-29*/ /*w44771 add for dhcp option 43, begin, 2006-10-10*/ if (strlen (option_43) > 0 ) { (void)tmpfile_writevalue("option_43", option_43); } /*w44771 add for dhcp option 43, end, 2006-10-10*/ }
int main() { int qid; key_t key; int len,i; struct message msg; /*根据不同的路径和关键表示产生标准的key*/ if ((key = ftok("/", 'a')) == -1) { perror("ftok"); exit(1); } /*创建消息队列*/ if ((qid = msgget(key,IPC_CREAT|0666)) == -1) { perror("msgget"); exit(1); } printf("Opened queue %d\n",qid); puts("Please enter the message to queue:"); for (i=0;i<3;i++) { if ((fgets((&msg)->msg_text, BUFSZ, stdin)) == NULL) { puts("no message"); exit(1); } msg.msg_type = getpid()+i; len = strlen(msg.msg_text); /*添加消息到消息队列*/ if ((msgsnd(qid, &msg, len, 0)) < 0) { perror("message posted"); exit(1); } } /*读取消息队列*/ for (i=0;i<3;i++) { if (msgrcv(qid, &msg, BUFSZ, getpid()+2-i, 0) < 0) { perror("msgrcv"); exit(1); } printf("message is:%s\n",(&msg)->msg_text); } /* 从系统内核中移走消息队列 */ if ((msgctl(qid, IPC_RMID, NULL)) < 0) { perror("msgctl"); exit(1); } exit(0); }
int main(){ key_t key = ftok(".",100); int msgid = msgget(key,0); int res = msgrcv(msgid,&msg1,sizeof(msg1),1,0); printf("接收%s成功,字节数%d\n",msg1.buf,res); }
int Process(int argc, const char* argv[]) { if(argc < 9) std::cout << "Not enough parameters" << std::endl; int LANE_DETECTOR = atoi(argv[1]); int LANE_ANALYZER = atoi(argv[2]); int SEND_DATA = atoi(argv[3]); int DATA_RECORD = atoi(argv[4]); int StartFrame = atoi(argv[5]); // FRAME_START int EndFrame = atoi(argv[6]); // FRAME_END double YAW_ANGLE = atof(argv[7]); // yaw - X double PITCH_ANGLE = atof(argv[8]); // pitch - Y std::cout << "/*************************************/" << std::endl; std::cout << "Input LANE_DETECTOR" << LANE_DETECTOR << std::endl; std::cout << "Input LANE_ANALYZER" << LANE_ANALYZER << std::endl; std::cout << "Input SEND_DATA" << SEND_DATA << std::endl; std::cout << "Input DATA_RECROD" << DATA_RECORD << std::endl; std::cout << "Input StartFrame" << StartFrame << std::endl; std::cout << "Input EndFrame" << EndFrame << std::endl; std::cout << "Input YAW_ANGLE" << YAW_ANGLE << std::endl; std::cout << "Input PITCH_ANGLE" << PITCH_ANGLE << std::endl; std::cout << "/*************************************/" << std::endl; int idx = StartFrame; //index for image sequence int sampleIdx = 1; //init sampling index char laneImg[100]; double initTime = (double)cv::getTickCount(); double intervalTime = 0; double execTime = 0; // Execute Time for Each Frame double pastTime = 0; double lastStartTime = (double)cv::getTickCount(); char key; double delay = 1; std::ofstream laneFeatureFile; if (DATA_RECORD){ InitRecordData(laneFeatureFile, FILE_LANE_FEATURE, laneFeatureName, NUM_LANE); } /* Parameters for Lane Detector */ cv::Mat laneMat; LaneDetector::LaneDetectorConf laneDetectorConf; std::vector<cv::Vec2f> hfLanes; std::vector<cv::Vec2f> lastHfLanes; std::vector<cv::Vec2f> preHfLanes; std::vector<double> LATSDBaselineVec; std::deque<LaneDetector::InfoCar> lateralOffsetDeque; std::deque<LaneDetector::InfoCar> LANEXDeque; std::deque<LaneDetector::InfoTLC> TLCDeque; LaneDetector::LaneFeature laneFeatures; double lastLateralOffset = 0; double lateralOffset = 0; // Lateral Offset int detectLaneFlag = -1; // init state -> normal state 0 int isChangeLane = 0; // Whether lane change happens int changeDone = 0; // Finish lane change int muWindowSize = 5; // Initial window size: 5 (sample) int sigmaWindowSize = 5; // Initial window size: 5 (sample) std::vector<float> samplingTime; /* Initialize Lane Kalman Filter */ cv::KalmanFilter laneKalmanFilter(8, 8, 0);//(rho, theta, delta_rho, delta_theta)x2 cv::Mat laneKalmanMeasureMat(8, 1, CV_32F, cv::Scalar::all(0));//(rho, theta, delta_rho, delta_theta) int laneKalmanIdx = 0; //Marker of start kalmam InitlaneFeatures(laneFeatures); GetSamplingTime(LANE_RECORD_FILE, samplingTime); if (LANE_DETECTOR) { /* Lane detect and tracking */ sprintf(laneImg, LANE_RAW_NAME , idx); laneMat = cv::imread(laneImg); LaneDetector::InitlaneDetectorConf(laneMat, laneDetectorConf, 2); // KIT 1, ESIEE 2 LaneDetector::InitLaneKalmanFilter(laneKalmanFilter, laneKalmanMeasureMat, laneKalmanIdx); } /* Inter-process communication */ key_t ipckey; int mq_id; struct { long type; char text[1024]; } laneMsg; if (SEND_DATA) { /* Generate the ipc key */ ipckey = ftok(KEY_PATH, 'a'); if(ipckey == -1){ printf("Key Error: %s\n", strerror(errno)); exit(1); } mq_id = msgget(ipckey, 0); if (mq_id == -1) { //MQ doesn't exit mq_id = msgget(ipckey, IPC_CREAT | IPC_EXCL | 0666); printf("LaneDetector creates a new MQ %d\n", mq_id); } else { //MQ does exit mq_id = msgget(ipckey, IPC_EXCL | 0666); printf("LaneDetector uses an existed MQ %d\n", mq_id); } //printf("Lane identifier is %d\n", mq_id); if(mq_id == -1) { throw std::logic_error("Can't build pipeline"); } //printf("This is the LaneDetectSim process, %d\n", getpid()); } double delayTime; if(idx == 1) delayTime = 0; else delayTime = samplingTime.at(idx - 2); /* Entrance of Process */ while (idx <= EndFrame) { double startTime = (double)cv::getTickCount(); /* Lane detect and tracking */ sprintf(laneImg, LANE_RAW_NAME , idx); laneMat = cv::imread(laneImg);//imshow("laneMat", laneMat); if (LANE_DETECTOR) { ProcessLaneImage(laneMat, laneDetectorConf, startTime, laneKalmanFilter, laneKalmanMeasureMat, laneKalmanIdx, hfLanes, lastHfLanes, lastLateralOffset, lateralOffset, isChangeLane, detectLaneFlag, idx, execTime, preHfLanes, changeDone, YAW_ANGLE, PITCH_ANGLE); } intervalTime = (startTime - lastStartTime)/ cv::getTickFrequency();//get the time between two continuous frames lastStartTime = startTime; // cout << "intervalTime: "<< intervalTime << endl; /* Generate lane indicators */ if (LANE_DETECTOR && LANE_ANALYZER) { /// First init the baseline, then get lane mass if( pastTime < TIME_BASELINE + delayTime){ /// Get lane baseline LaneDetector::GetLaneBaseline(sampleIdx, SAMPLING_TIME, muWindowSize, sigmaWindowSize, lateralOffset, LATSDBaselineVec, lateralOffsetDeque, LANEXDeque, TLCDeque, laneFeatures, intervalTime); //idx_baseline = sampleIdx; } else { //sampleIdx -= idx_baseline; LaneDetector::GenerateLaneIndicators(sampleIdx, SAMPLING_TIME, muWindowSize, sigmaWindowSize, lateralOffset, lateralOffsetDeque, LANEXDeque, TLCDeque, laneFeatures, intervalTime); //! LATSD char *text_LATSD = new char[30]; sprintf(text_LATSD, "L1. LATSD: %.4f", laneFeatures.LATSD); cv::putText(laneMat, text_LATSD, cv::Point(0, 70), cv::FONT_HERSHEY_SIMPLEX, 0.3, CV_RGB(0,255,0)); delete text_LATSD; //! LATMEAN char *text_LATMEAN = new char[30]; sprintf(text_LATMEAN, "L2. LATMEAN: %.4f", laneFeatures.LATMEAN); cv::putText(laneMat, text_LATMEAN, cv::Point(0, 80), cv::FONT_HERSHEY_SIMPLEX, 0.3, CV_RGB(0,255,0)); delete text_LATMEAN; //! LANEDEV char *text_LANEDEV = new char[30]; sprintf(text_LANEDEV, "L3. LANEDEV: %.4f", laneFeatures.LANEDEV); cv::putText(laneMat, text_LANEDEV, cv::Point(0, 90), cv::FONT_HERSHEY_SIMPLEX, 0.3, CV_RGB(0,255,0)); delete text_LANEDEV; //! LANEX char *text_LANEX = new char[30]; sprintf(text_LANEX, "L4. LANEX: %.4f", laneFeatures.LANEX); cv::putText(laneMat, text_LANEX, cv::Point(0, 100), cv::FONT_HERSHEY_SIMPLEX, 0.3, CV_RGB(0,255,0)); delete text_LANEX; //! TLC char *text_TLC = new char[30]; sprintf(text_TLC, "L5. TLC: %.4f", laneFeatures.TLC); cv::putText(laneMat, text_TLC, cv::Point(0, 110), cv::FONT_HERSHEY_SIMPLEX, 0.3, CV_RGB(0,255,0)); delete text_TLC; //! TLC_2s char *text_TLC_2s = new char[30]; sprintf(text_TLC_2s, "L6. TLC_2s: %d", laneFeatures.TLC_2s); cv::putText(laneMat, text_TLC_2s, cv::Point(0, 120), cv::FONT_HERSHEY_SIMPLEX, 0.3, CV_RGB(0,255,0)); delete text_TLC_2s; char *text_TLCF_2s = new char[50]; sprintf(text_TLCF_2s, "L7. Fraction_TLC_2s: %f", laneFeatures.TLCF_2s); cv::putText(laneMat, text_TLCF_2s, cv::Point(0, 130), cv::FONT_HERSHEY_SIMPLEX, 0.3, CV_RGB(0,255,0)); delete text_TLCF_2s; //! TLC_halfs char *text_TLC_halfs = new char[30]; sprintf(text_TLC_halfs, "L8. TLC_halfs: %d", laneFeatures.TLC_halfs); cv::putText(laneMat, text_TLC_halfs, cv::Point(0, 140), cv::FONT_HERSHEY_SIMPLEX, 0.3, CV_RGB(0,255,0)); delete text_TLC_halfs; char *text_TLCF_halfs = new char[50]; sprintf(text_TLCF_halfs, "L9. Fraction_TLC_halfs: %f", laneFeatures.TLCF_halfs); cv::putText(laneMat, text_TLCF_halfs, cv::Point(0, 150), cv::FONT_HERSHEY_SIMPLEX, 0.3, CV_RGB(0,255,0)); delete text_TLCF_halfs; //! TLC_min char *text_TLC_min = new char[30]; sprintf(text_TLC_min, "L10. TLC_min: %.4f", laneFeatures.TLC_min); cv::putText(laneMat, text_TLC_min, cv::Point(0, 160), cv::FONT_HERSHEY_SIMPLEX, 0.3, CV_RGB(0,255,0)); delete text_TLC_min; }//end if }//end Generate Lane Indicators if(IMAGE_RECORD){ char *text = new char[100]; sprintf(text, LANE_RECORD_IMAGE, idx); cv::imwrite(text, laneMat); delete text; } /* Send the datas as string to fusion center */ if(LANE_DETECTOR & SEND_DATA) { char *str = new char[1024]; memset(str, 0, 1024); CodeMsg(laneFeatures, str); strcpy(laneMsg.text, str);//!!! overflow laneMsg.type = 1; //printf("Data sends: %s\n", laneMsg.text); //! 0 will cause a block/ IPC_NOWAIT will close the app. if(msgsnd(mq_id, &laneMsg, sizeof(laneMsg), 0) == -1) { throw std::runtime_error("LaneDetectSim: msgsnd failed!"); } delete str; } /* Adjust the interval time within fixed frequency */ double execFreq; do { execFreq = 1.0 / (((double)cv::getTickCount() - startTime)/cv::getTickFrequency()); pastTime = ((double)cv::getTickCount() - initTime)/cv::getTickFrequency() + delayTime; }while ( pastTime < samplingTime.at(idx-1) ); // }while(execFreq > SAMPLING_FREQ); // }while(pastTime < (double)sampleIdx/SAMPLING_FREQ); /* Record lane features */ if (DATA_RECORD) { RecordLaneFeatures(laneFeatureFile, laneFeatures, execTime, pastTime); }//end if char *text = new char[30]; sprintf(text, "past time: %.2f sec", pastTime); cv::putText(laneMat, text, cv::Point(0, laneMat.rows-5), cv::FONT_HERSHEY_SIMPLEX, 0.8, CV_RGB(0,255,0)); sprintf(text, "Adjusted Freq: %.2f Hz", execFreq); cv::putText(laneMat, text, cv::Point(0, 60), cv::FONT_HERSHEY_SIMPLEX, 0.8, CV_RGB(0, 255, 0)); delete text; cv::imshow("Lane System", laneMat); // cv::moveWindow("Lane System", 790, 30); key = cv::waitKey(delay); if (key == 'q' || key == 'Q' || 27 == (int)key) //Esc q\Q\key to stop break; else if(key == 's' || key == 'S') delay = 0; else delay = 1; /* Update the sampling index */ sampleIdx++;//update the sampling index idx++; // if(idx == FRAME_STOP1) // idx = FRAME_RESTART1; // if(idx == FRAME_STOP2) // idx = FRAME_RESTART2; }//end while loop laneFeatureFile.close(); cv::destroyAllWindows(); return 0; }
int main(int argc,char* argv[]) { signal(SIGINT,sig); if(argc !=4) { printf("error args\n"); return -1; } int fdr; fdr=open(argv[1],O_RDONLY); if(-1==fdr) { perror("open1"); return -1; } int fdw; fdw=open(argv[2],O_WRONLY); if(-1==fdw) { perror("open2"); return -1; } // printf("fdr=%d,fdw=%d\n",fdr,fdw); printf("welcome\n"); //产生key key_t skey; skey = ftok(argv[3],PROJ_ID); if(-1 == skey){ perror("ftok"); return -1; } //共享内存 int shmid; shmid = shmget(skey,1<<12,0600|IPC_CREAT); if(-1 == shmid){ perror("shmget"); return -1; } char *p; p = (char*)shmat(shmid,NULL,0); if((char*)-1 == p){ perror("shmat"); return -1; } bzero(p,sizeof(p)); //printf("the p is %s\n",p); int ret; //信号量 int semid; semid = semget(skey,2,0600|IPC_CREAT); unsigned short arr[2]; arr[0] = 1; arr[1] = 0; ret = semctl(semid,0,SETALL,arr); if(-1 == ret){ perror("semctl"); return -1; } struct sembuf sop; bzero(&sop,sizeof(sop)); sop.sem_num = 0; sop.sem_op = -1; sop.sem_flg = SEM_UNDO; struct sembuf sov; bzero(&sov,sizeof(sov)); sov.sem_num = 0; sov.sem_op = 1; sov.sem_flg = SEM_UNDO; struct sembuf produce; bzero(&produce,sizeof(produce)); produce.sem_num = 1; produce.sem_op = 1; produce.sem_flg = SEM_UNDO; char buf[128]; fd_set readset; while(!qflag) { FD_ZERO(&readset); FD_SET(STDIN_FILENO,&readset); FD_SET(fdr,&readset); ret=select(fdr+1,&readset,NULL,NULL,NULL); if(ret >0) { if(FD_ISSET(fdr,&readset)) //如果fdr可读 { bzero(buf,sizeof(buf)); if(read(fdr,buf,sizeof(buf))>0) { //ret = semctl(semid,0,GETVAL); //printf("before the ret is %d\n",ret); semop(semid,&sop,1); //ret = semctl(semid,0,GETVAL); //printf("in sop %d\n",ret); memcpy(p,buf,sizeof(buf)); //printf("the p id %s\n",p); semop(semid,&produce,1); semop(semid,&sov,1); //ret = semctl(semid,0,GETVAL); //printf("sov the ret is %d\n",ret); //ret = semctl(semid,1,GETVAL); //printf("procude the ret is %d\n",ret); // printf("%s\n",buf); } } if(FD_ISSET(STDIN_FILENO,&readset))//如果标准输入可读 { bzero(buf,sizeof(buf)); if((ret=read(STDIN_FILENO,buf,sizeof(buf)))>0) { write(fdw,buf,ret-1); semop(semid,&sop,1); //ret = semctl(semid,0,GETVAL); //printf("in sop %d\n",ret); memcpy(p,buf,ret - 1); //printf("the p id %s\n",p); semop(semid,&produce,1); semop(semid,&sov,1); //ret = semctl(semid,0,GETVAL); }else{ write(fdw,"bye",3); break; } } } } close(fdr); close(fdw); shmdt(p); shmctl(shmid,IPC_RMID,NULL); return 0; }
/* ========================================================================= */ int shm_connect(ShmLink *cont, const char* key_path, const int key_int, unsigned int size) { int semflag = 0; key_t key; struct shmid_ds shm_desc; memset(&shm_desc, 0, sizeof shm_desc); if (cont == NULL || key_path == NULL) return -1; if ((key=ftok(key_path,key_int)) < 0) return -2; /* Try to create shm segment */ if ((cont->shm_id = shmget(key, (size_t)size, 0666|IPC_CREAT|IPC_EXCL)) < 0) { if (errno == EEXIST) /* Shm segment for this key exists already */ { if ((cont->shm_id = shmget(key, 1, 0666)) < 0) /*Get ID of existing seg*/ { (void)snprintf(cont->err_msg, SHMCI_EMSG_SIZE, "[%s:%d] Error in shmget() for segment. %s", _FILE_, __LINE__, strerror(errno)); return -4; } if (shmctl(cont->shm_id, IPC_STAT, &shm_desc) < 0) { (void)snprintf(cont->err_msg, SHMCI_EMSG_SIZE, "[%s:%d] Error getting segment stat. %s", _FILE_, __LINE__, strerror(errno)); return -5; } if (shm_desc.shm_nattch == 0) /* Segment unused - delete it and create anew */ { semflag = 1; /* Flag - recreate semaphore */ if (shmctl(cont->shm_id, IPC_RMID, NULL) < 0) { (void)snprintf(cont->err_msg, SHMCI_EMSG_SIZE, "[%s:%d] Error deleting old segment. %s", _FILE_, __LINE__, strerror(errno)); return -6; } if ((cont->shm_id = shmget(key, (size_t)size, 0666|IPC_CREAT)) < 0) { (void)snprintf(cont->err_msg, SHMCI_EMSG_SIZE, "[%s:%d] Error in shmget() for segment. %s", _FILE_, __LINE__, strerror(errno)); return -7; } cont->shm_size = size; } else /* Segment is already in use */ { cont->shm_size = (unsigned int)shm_desc.shm_segsz; } } else { (void)snprintf(cont->err_msg, SHMCI_EMSG_SIZE, "[%s:%d] Unexpected error in shmget() for segment. %s", _FILE_, __LINE__, strerror(errno)); return -8; } } else /* Segment created */ { cont->shm_size=size; } /* Attach new shm segment to address space */ if ((cont->ptr = shmat(cont->shm_id, NULL, 0)) == (void*)-1) { (void)snprintf(cont->err_msg, SHMCI_EMSG_SIZE, "[%s:%d] Error attaching segment. %s", _FILE_, __LINE__, strerror(errno)); return -9; } /* Try to create semaphore */ if ((cont->sem_id = semget(key, 1, 0666|IPC_CREAT|IPC_EXCL)) < 0) { if (errno == EEXIST) /* Semaphore set for this key exists already */ { if ((cont->sem_id = semget(key, 1, 0666)) < 0) /*Get ID of existing sem*/ { (void)snprintf(cont->err_msg, SHMCI_EMSG_SIZE, "[%s:%d] Error in semget() for semaphore. %s", _FILE_, __LINE__, strerror(errno)); return -10; } if (semflag != 0) { if (semctl(cont->sem_id, 0, IPC_RMID) < 0) { (void)snprintf(cont->err_msg, SHMCI_EMSG_SIZE, "[%s:%d] Error deleting semaphore. %s", _FILE_, __LINE__, strerror(errno)); return -11; } if ((cont->sem_id = semget(key, 1, 0666|IPC_CREAT)) < 0) { (void)snprintf(cont->err_msg, SHMCI_EMSG_SIZE, "[%s:%d] Error in semget() for semaphore. %s", _FILE_, __LINE__, strerror(errno)); return -12; } } } else { (void)snprintf(cont->err_msg, SHMCI_EMSG_SIZE, "[%s:%d] Unexpected error in semget() for semaphore. %s", _FILE_, __LINE__, strerror(errno)); return -13; } } (void)strncpy(cont->err_msg, "No errors detected", SHMCI_EMSG_SIZE); return 0; }
int main(int argc, char** argv) { //Make sure command line is correct if (argc != 3) { fprintf(stderr, "USAGE: %s <DATABASE FILE> <NUM OF THREADS>\n", argv[0]); return 0; } int num_threads = atoi(argv[2]); // valid number of threads if(num_threads<1) { fprintf(stderr, "Number of threads must be greater than 0!\n"); return 0; } // populate hashtable with file from argument 1 fillHashtable(argv[1]); // generate key for message queue id key_t key = ftok("/bin/ls", 'O'); // Was the key allocation successful ? if(key < 0) { perror("ftok"); exit(-1); } /* Allocate the message queue if it does not already exist. * This function returns the id of the queue. */ msqid = msgget(key, 0666 | IPC_CREAT); // Was the allocation a success ? if(msqid < 0) { perror("msgget"); exit(-1); } signal(SIGINT, signalHandlerFunc); // create thread to insert records and initialize pthread_t insert_threads[NUM_INSERT_THRDS]; for(int i=0;i<NUM_INSERT_THRDS;i++) { if (pthread_create(&insert_threads[i], NULL, insertRandRecThread, NULL) <0) { perror("pthread_create insertRecord"); exit(-1); } } // make an array of threads of num_threads pthread_t record_thread[num_threads]; // initialize thread to get record and send result for(int i=0;i<num_threads;i++) { if(pthread_create(&record_thread[i], NULL, threadRecordFindAndSend, NULL) < 0) { perror("pthread_create getRecord"); exit(-1); } } // receive messages constantly until the signal is interrupted while(!exit_thread) { rcvMessage(); } // wake up all threads when control c is hit pthread_cond_broadcast(&pool_cond); // wait for record inserter thread to finish execution for(int i=0;i<NUM_INSERT_THRDS;i++) { pthread_join(insert_threads[i], NULL); } // wait for record getter threads to finish execution for(int i=0;i<num_threads;i++) { pthread_join(record_thread[i], NULL); } // deallocate the queue if(msgctl(msqid, IPC_RMID, NULL) < 0) { perror("msgctl"); } return 0; }
int main(int argc, char const * argv[]) { const char * config_file; int connection_numer = 0, ret, pid; short vals[SEM_SIZE] = {1, 1}; key_t key = ftok("database.sql", KEY_ID); key_t key_db = ftok("database.sql", KEY_DB_ID); switch(argc) { case 1: { config_file = CONFIG_FILE_DEFAULT; } break; case 2: { config_file = argv[1]; } break; default: { fprintf(stderr, "Usage: 'server.app [config_file]'.\n"); exit(EXIT_FAILURE); } } pcg32_srandom(time(NULL), (intptr_t)&connection_numer); server_sems = sem_make(key, SEM_SIZE, vals); if(server_sems == -1) { fprintf(stderr, "1 Can't create neccessary data to operate.\n"); exit(EXIT_FAILURE); } bettors = mmap(NULL, sizeof(*bettors), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0); if(bettors == MAP_FAILED) { fprintf(stderr, "2 Can't create neccessary data to operate.\n"); exit(EXIT_FAILURE); } clients = mmap(NULL, sizeof(*clients), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0); if(clients == MAP_FAILED) { fprintf(stderr, "3 Can't create neccessary data to operate.\n"); exit(EXIT_FAILURE); } winner = mmap(NULL, sizeof(*winner) * MAX_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0); if(winner == MAP_FAILED) { fprintf(stderr, "4 Can't create neccessary data to operate.\n"); exit(EXIT_FAILURE); } *bettors = 0; *clients = 0; memset(winner, 0, sizeof(*winner) * MAX_SIZE); if(!log_open()) { fprintf(stderr, "Can't connect logging server.\n"); //exit(EXIT_FAILURE); } database = smemory_open(key_db); // TODO: define 8080 if(database == NULL) { fprintf(stderr, "Can't reach the database.\n"); exit(EXIT_FAILURE); } connection = server_open(config_file); if(connection == NULL) { fprintf(stderr, "Can't create the main connection.\n"); exit(EXIT_FAILURE); } signal(SIGINT, handle_int); signal(SIGCHLD, handle_int); while(TRUE) { connection_t connection_accepted; connection_accepted = server_accept(connection); if(connection_accepted == NULL) { log_send(LEVEL_ERROR, "[MAIN SV] Can't connect to client."); exit(EXIT_FAILURE); // TODO: Exit? } connection_numer++; (*clients)++; pid = fork(); if(pid == -1) { log_send(LEVEL_ERROR, "[MAIN SV] Can't assign resources to client."); exit(EXIT_FAILURE); // TODO: Exit? } if(!pid) { // Child process // sem_lock(server_sems, 1); // (*clients)++; // sem_unlock(server_sems, 1); server_ajar(connection); log_send(LEVEL_INFO, "[CHILD SV] Disconnecting main connection."); ret = handle(connection_accepted); if(ret == EXIT_FAILURE) { log_send(LEVEL_ERROR, "[CHILD SV] There was an error handling client."); } server_close(connection_accepted); log_send(LEVEL_INFO, "[CHILD SV] Closed client connection."); // sem_lock(server_sems, 1); // (*clients)--; // sem_unlock(server_sems, 1); exit(ret); } log_send(LEVEL_INFO, "[MAIN SV] Disconnecting new connection."); server_ajar(connection_accepted); } server_close(connection); if(!db_close(database)) { log_send(LEVEL_ERROR, "[MAIN SV] Couldn't correctly logout from database."); } log_close(); sem_remove(server_sems); return 0; }
bool QVFbScreen::connect(const QString &displaySpec) { QStringList displayArgs = displaySpec.split(QLatin1Char(':')); if (displayArgs.contains(QLatin1String("Gray"))) grayscale = true; key_t key = ftok(QT_VFB_MOUSE_PIPE(displayId).toLocal8Bit(), 'b'); if (key == -1) return false; #if Q_BYTE_ORDER == Q_BIG_ENDIAN #ifndef QT_QWS_FRAMEBUFFER_LITTLE_ENDIAN if (displayArgs.contains(QLatin1String("littleendian"))) #endif QScreen::setFrameBufferLittleEndian(true); #endif int shmId = shmget(key, 0, 0); if (shmId != -1) d_ptr->shmrgn = (unsigned char *)shmat(shmId, 0, 0); else return false; if ((long)d_ptr->shmrgn == -1 || d_ptr->shmrgn == 0) { qDebug("No shmrgn %ld", (long)d_ptr->shmrgn); return false; } d_ptr->hdr = (QVFbHeader *)d_ptr->shmrgn; data = d_ptr->shmrgn + d_ptr->hdr->dataoffset; dw = w = d_ptr->hdr->width; dh = h = d_ptr->hdr->height; d = d_ptr->hdr->depth; switch (d) { case 1: setPixelFormat(QImage::Format_Mono); break; case 8: setPixelFormat(QImage::Format_Indexed8); break; case 12: setPixelFormat(QImage::Format_RGB444); break; case 15: setPixelFormat(QImage::Format_RGB555); break; case 16: setPixelFormat(QImage::Format_RGB16); break; case 18: setPixelFormat(QImage::Format_RGB666); break; case 24: setPixelFormat(QImage::Format_RGB888); break; case 32: setPixelFormat(QImage::Format_ARGB32_Premultiplied); break; } lstep = d_ptr->hdr->linestep; // Handle display physical size spec. int dimIdxW = -1; int dimIdxH = -1; for (int i = 0; i < displayArgs.size(); ++i) { if (displayArgs.at(i).startsWith(QLatin1String("mmWidth"))) { dimIdxW = i; break; } } for (int i = 0; i < displayArgs.size(); ++i) { if (displayArgs.at(i).startsWith(QLatin1String("mmHeight"))) { dimIdxH = i; break; } } if (dimIdxW >= 0) { bool ok; int pos = 7; if (displayArgs.at(dimIdxW).at(pos) == QLatin1Char('=')) ++pos; int pw = displayArgs.at(dimIdxW).mid(pos).toInt(&ok); if (ok) { physWidth = pw; if (dimIdxH < 0) physHeight = dh*physWidth/dw; } } if (dimIdxH >= 0) { bool ok; int pos = 8; if (displayArgs.at(dimIdxH).at(pos) == QLatin1Char('=')) ++pos; int ph = displayArgs.at(dimIdxH).mid(pos).toInt(&ok); if (ok) { physHeight = ph; if (dimIdxW < 0) physWidth = dw*physHeight/dh; } } if (dimIdxW < 0 && dimIdxH < 0) { const int dpi = 72; physWidth = qRound(dw * 25.4 / dpi); physHeight = qRound(dh * 25.4 / dpi); } qDebug("Connected to VFB server %s: %d x %d x %d %dx%dmm (%dx%ddpi)", displaySpec.toLatin1().data(), w, h, d, physWidth, physHeight, qRound(dw*25.4/physWidth), qRound(dh*25.4/physHeight) ); size = lstep * h; mapsize = size; screencols = d_ptr->hdr->numcols; memcpy(screenclut, d_ptr->hdr->clut, sizeof(QRgb) * screencols); connected = this; if (qgetenv("QT_QVFB_BGR").toInt()) pixeltype = BGRPixel; return true; }
PR_IMPLEMENT(PRSem *) PR_OpenSemaphore( const char *name, PRIntn flags, PRIntn mode, PRUintn value) { PRSem *sem; key_t key; union semun arg; struct sembuf sop; struct semid_ds seminfo; #define MAX_TRIES 60 PRIntn i; char osname[PR_IPC_NAME_SIZE]; if (_PR_MakeNativeIPCName(name, osname, sizeof(osname), _PRIPCSem) == PR_FAILURE) { return NULL; } /* Make sure the file exists before calling ftok. */ if (flags & PR_SEM_CREATE) { int osfd = open(osname, O_RDWR|O_CREAT, mode); if (-1 == osfd) { _PR_MD_MAP_OPEN_ERROR(errno); return NULL; } if (close(osfd) == -1) { _PR_MD_MAP_CLOSE_ERROR(errno); return NULL; } } key = ftok(osname, NSPR_IPC_KEY_ID); if ((key_t)-1 == key) { _PR_MD_MAP_DEFAULT_ERROR(errno); return NULL; } sem = PR_NEW(PRSem); if (NULL == sem) { PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0); return NULL; } if (flags & PR_SEM_CREATE) { sem->semid = semget(key, 1, mode|IPC_CREAT|IPC_EXCL); if (sem->semid >= 0) { /* creator of a semaphore is responsible for initializing it */ arg.val = 0; if (semctl(sem->semid, 0, SETVAL, arg) == -1) { _PR_MD_MAP_DEFAULT_ERROR(errno); PR_DELETE(sem); return NULL; } /* call semop to set sem_otime to nonzero */ sop.sem_num = 0; sop.sem_op = value; sop.sem_flg = 0; if (semop(sem->semid, &sop, 1) == -1) { _PR_MD_MAP_DEFAULT_ERROR(errno); PR_DELETE(sem); return NULL; } return sem; } if (errno != EEXIST || flags & PR_SEM_EXCL) { _PR_MD_MAP_DEFAULT_ERROR(errno); PR_DELETE(sem); return NULL; } } sem->semid = semget(key, 1, NSPR_SEM_MODE); if (sem->semid == -1) { _PR_MD_MAP_DEFAULT_ERROR(errno); PR_DELETE(sem); return NULL; } for (i = 0; i < MAX_TRIES; i++) { arg.buf = &seminfo; semctl(sem->semid, 0, IPC_STAT, arg); if (seminfo.sem_otime != 0) break; sleep(1); } if (i == MAX_TRIES) { PR_SetError(PR_IO_TIMEOUT_ERROR, 0); PR_DELETE(sem); return NULL; } return sem; }
int main(int argc, char* argv[]) { struct utas utasok[maxCap]; struct jarat jaratok[maxCap]; int meret = 3; int utas_meret = 0; int sor; int i,z,f; char* tmp1; char* tmp2; char* tmp_nev; char* tmp_uti_cell; char* tmp_tel; jarat_inicializalas(jaratok); char valasz = ' '; fflush(stdin); menu(); while( valasz != '0' ) { scanf( "%c", &valasz ); switch(valasz) { case '1': jarat_infok(jaratok, utasok, meret, utas_meret); menu(); break; case '2': tmp2 = malloc(sizeof(char) * 64); tmp1 = malloc(sizeof(char) * 64); printf("Uj varos: "); fflush(stdin); scanf("%s", tmp1); jaratok[meret].nev = tmp1; printf("Uj indulasi ido: "); fflush(stdin); scanf("%s", tmp2); jaratok[meret].ido = tmp2; meret++; menu(); break; case '3': jarat_kiiras(jaratok, meret); fflush(stdin); scanf("%d" , &sor); printf("%d : ", sor); if(sor != meret - 1) { for(i = 0; i < meret - 1; i++) { if(i >= sor) { printf("%s : ", jaratok[i].nev); jaratok[i].nev = jaratok[i+1].nev; jaratok[i].ido = jaratok[i+1].ido; } } } meret--; menu(); break; case '4': tmp_nev = malloc(sizeof(char) * 64); tmp_uti_cell = malloc(sizeof(char) * 64); tmp_tel = malloc(sizeof(char) * 64); printf("Uj nev: "); fflush(stdin); scanf("%s", tmp_nev); utasok[utas_meret].nev = tmp_nev; printf("Uj uticell: "); fflush(stdin); scanf("%s", tmp_uti_cell); utasok[utas_meret].uti_cell = tmp_uti_cell; printf("Uj telefon: "); fflush(stdin); scanf("%s", tmp_tel); utasok[utas_meret].telefon = tmp_tel; utasok[utas_meret].ido[0] = '\0'; time_t most = time(NULL); strcat(utasok[utas_meret].ido, ctime(&most)); utasok[utas_meret].ido[strlen(utasok[utas_meret].ido)-1] = '\0'; utas_meret++; menu(); break; case '5': utas_kiiras(utasok, utas_meret); fflush(stdin); scanf("%d" , &sor); if(sor <= utas_meret - 1) { for(i = 0; i < utas_meret - 1; i++) { if(i >= sor) { printf("%s : ", utasok[i].nev); utasok[i].nev = utasok[i+1].nev; for(z = 0; z < strlen(utasok[i+1].ido); z++) { utasok[i].ido[z] = utasok[i+1].ido[z]; } utasok[i].uti_cell = utasok[i+1].uti_cell; utasok[i].telefon = utasok[i+1].telefon; } } utas_meret--; } menu(); break; case '6': utas_kiiras(utasok, utas_meret); tmp_nev = malloc(sizeof(char) * 64); tmp_uti_cell = malloc(sizeof(char) * 64); tmp_tel = malloc(sizeof(char) * 64); fflush(stdin); scanf("%d" , &sor); printf("Uj nev: "); fflush(stdin); scanf("%s", tmp_nev); utasok[sor].nev = tmp_nev; printf("Uj uticell: "); fflush(stdin); scanf("%s", tmp_uti_cell); utasok[sor].uti_cell = tmp_uti_cell; printf("Uj telefon: "); fflush(stdin); scanf("%s", tmp_tel); utasok[sor].telefon = tmp_tel; utasok[sor].ido[0] = '\0'; time_t most1 = time(NULL); strcat(utasok[sor].ido, ctime(&most1)); utasok[sor].ido[strlen(utasok[sor].ido)-1] = '\0'; menu(); break; case '7': f = open("uber.txt", O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR); int i; for(i = 0; i < meret; i++) { write(f, jaratok[i].nev, strlen(jaratok[i].nev)); write(f, " ", 1); write(f, jaratok[i].ido, strlen(jaratok[i].ido)); write(f, "\n", 1); int k; for(k = 0; k < utas_meret; k++) { if(!strcmp(jaratok[i].nev, utasok[k].uti_cell)) { write(f, utasok[k].nev, strlen(utasok[k].nev)); write(f, " ", 1); write(f, utasok[k].ido, strlen(utasok[k].ido)); write(f, " ", 1); write(f, utasok[k].uti_cell, strlen(utasok[k].uti_cell)); write(f, " ", 1); write(f, utasok[k].telefon, strlen(utasok[k].telefon)); write(f, "\n", 1); } } } close(f); menu(); break; } if(valasz == '8') { break; } } int pipefd[2]; // unnamed pipe file descriptor array pid_t pid; char *becs[] = {"atilla", "peter", "anna"}; char *praga[] = {"emoke"}; srand(time(NULL)); int uzenetsor, status; if (pipe(pipefd) == -1) { perror("Hiba a pipe nyitaskor!"); exit(EXIT_FAILURE); } pid = fork(); // creating parent-child processes if (pid == -1) { perror("Fork hiba"); exit(EXIT_FAILURE); } key_t kulcs; kulcs = ftok(argv[0],1); uzenetsor = msgget( kulcs, 0600 | IPC_CREAT ); if ( uzenetsor < 0 ) { perror("msgget"); return 1; } signal(SIGRTMIN, handler); char kapott[100] =""; if(pid > 0) // szulofolyamat { printf("elkuldom az utas listat\n"); close(pipefd[0]); fflush(NULL); int i; for(i = 0; i < 3; i++) { write(pipefd[1], becs[i], strlen(becs[i])); write(pipefd[1], " " , 1); } fflush(NULL); close(pipefd[1]); //wait(NULL); for(i = 0; i < 3; i++) { fogad(uzenetsor); } pause(); printf("idegenvezeto befejezte\n"); wait(NULL); } else // gyerek folyamat { close(pipefd[1]); read(pipefd[0], kapott, sizeof(kapott)); printf("kapott: %s\n", kapott); close(pipefd[0]); int i; for(i = 0; i < 3; i++) { int r = rand()%5+1; char t[10]; sprintf(t, "%d", r); kuld(uzenetsor, t); } sleep(3); kill(getppid(),SIGRTMIN); } return 0; }
//create worker child proccess static int swFactoryProcess_manager_start(swFactory *factory) { swFactoryProcess *object = factory->object; int i, pid, ret; int writer_pti; swServer *serv = factory->ptr; #if SW_WORKER_IPC_MODE == 2 #define _SW_PATH_BUF_LEN 128 //这里使用ftok来获取消息队列的key char path_buf[_SW_PATH_BUF_LEN]; char *path_ptr = getcwd(path_buf, _SW_PATH_BUF_LEN); //读数据队列 if(swQueueMsg_create(&object->rd_queue, 1, ftok(path_ptr, 1), 1) < 0) { swError("[Master] swPipeMsg_create[In] fail. Error: %s [%d]", strerror(errno), errno); return SW_ERR; } //为TCP创建写队列 if (serv->have_tcp_sock == 1) { //写数据队列 if(swQueueMsg_create(&object->wt_queue, 1, ftok(path_ptr, 2), 1) < 0) { swError("[Master] swPipeMsg_create[out] fail. Error: %s [%d]", strerror(errno), errno); return SW_ERR; } } #else object->pipes = sw_calloc(object->worker_num, sizeof(swPipe)); if (object->pipes == NULL) { swError("malloc[worker_pipes] fail. Error: %s [%d]", strerror(errno), errno); return SW_ERR; } //worker进程的pipes for (i = 0; i < object->worker_num; i++) { if (swPipeUnsock_create(&object->pipes[i], 1, SOCK_DGRAM) < 0) { swError("create unix socket[1] fail"); return SW_ERR; } object->workers[i].pipe_master = object->pipes[i].getFd(&object->pipes[i], 1); object->workers[i].pipe_worker = object->pipes[i].getFd(&object->pipes[i], 0); } #endif if (serv->task_worker_num > 0) { if (swProcessPool_create(&SwooleG.task_workers, serv->task_worker_num, serv->max_request)< 0) { swWarn("[Master] create task_workers fail"); return SW_ERR; } //设置指针和回调函数 SwooleG.task_workers.ptr = serv; SwooleG.task_workers.onTask = swTaskWorker_onTask; if (serv->onWorkerStart != NULL) { SwooleG.task_workers.onWorkerStart = swTaskWorker_onWorkerStart; } } pid = fork(); switch (pid) { //创建manager进程 case 0: for (i = 0; i < object->worker_num; i++) { // close(worker_pipes[i].pipes[0]); writer_pti = (i % object->writer_num); object->workers[i].writer_id = writer_pti; pid = swFactoryProcess_worker_spawn(factory, i); if (pid < 0) { swError("Fork worker process fail"); return SW_ERR; } else { object->workers[i].pid = pid; } } //创建task_worker进程 if (serv->task_worker_num > 0) { swProcessPool_start(&SwooleG.task_workers); } //标识为管理进程 SwooleG.process_type = SW_PROCESS_MANAGER; ret = swFactoryProcess_manager_loop(factory); exit(ret); break; //主进程 default: SwooleGS->manager_pid = pid; //TCP需要writer线程 if (serv->have_tcp_sock == 1) { int ret = swFactoryProcess_writer_start(factory); if (ret < 0) { return SW_ERR; } } #if SW_WORKER_IPC_MODE != 2 for (i = 0; i < object->worker_num; i++) { writer_pti = (i % object->writer_num); object->workers[i].writer_id = writer_pti; if (serv->have_tcp_sock == 1) { //将写pipe设置到writer的reactor中 object->writers[writer_pti].reactor.add(&(object->writers[writer_pti].reactor), object->workers[i].pipe_master, SW_FD_PIPE); } } #endif break; case -1: swError("[swFactoryProcess_worker_start]fork manager process fail"); return SW_ERR; } return SW_OK; }
int main(int argc, char* argv[]) { /********/ /*GLOBAL*/ /********/ int semid; int shmid; struct sembuf buff[8]; void *shm_mem; union semun semunion; unsigned short sems[5]= {0, 0, 0, 0, 0}; int i= 3; int count = 1; int fileid; semid = semget(ftok(argv[0], 1), 5, IPC_CREAT | 0664); shmid = shmget(ftok(argv[0], 2), BUFF_SIZE+4, IPC_CREAT | 0664); if (argc == 1) { /********/ /*READER*/ /********/ addtobuff(&buff[0], SEM_READER, 0, IPC_NOWAIT); addtobuff(&buff[1], SEM_SYNC, 0, IPC_NOWAIT); addtobuff(&buff[2], SEM_READER, +1, SEM_UNDO); semop(semid, buff, 3); if (errno == EAGAIN) { fprintf(stderr, "\n Reader already exists\n"); exit(EXIT_FAILURE); } addtobuff(&buff[0], SEM_WRITER, -1, 0); addtobuff(&buff[1], SEM_WRITER, +1, 0); addtobuff(&buff[2], SEM_SYNC, +1, SEM_UNDO); addtobuff(&buff[3], SEM_FULL, +1, SEM_UNDO); semop(semid, buff, 4); addtobuff(&buff[0], SEM_WRITER, -1, IPC_NOWAIT); addtobuff(&buff[1], SEM_WRITER, +1, 0); addtobuff(&buff[2], SEM_SYNC, -2, 0); addtobuff(&buff[3], SEM_SYNC, +2, 0); semop(semid, buff, 4); if (errno == EAGAIN) { fprintf(stderr, "\n Sync error\n"); exit(EXIT_FAILURE); } shm_mem= shmat(shmid, NULL, 0); while (1) { addtobuff(&buff[0], SEM_WRITER, -1, IPC_NOWAIT); addtobuff(&buff[1], SEM_WRITER, +1, 0); addtobuff(&buff[2], SEM_EMPTY, 0, 0); addtobuff(&buff[3], SEM_EMPTY, +1, 0); semop(semid, buff, 4); if (semctl(semid, SEM_SYNC, GETVAL) == 1) { fprintf(stderr, "\n No writer\n"); semunion.array = sems; semctl(semid, SEM_READER, SETALL, semunion); exit(EXIT_FAILURE); } count = *((int*)shm_mem); if (count == 0) break; count = write(1, shm_mem+4, count); addtobuff(&buff[0], SEM_FULL, -1, 0); semop(semid, buff, 1); } addtobuff(&buff[0], SEM_FULL, -1, 0); semop(semid, buff, 1); addtobuff(&buff[0], SEM_SYNC, 0, 0); semop(semid, buff, 1); } else if (argc == 2) { /********/ /*WRITER*/ /********/ addtobuff(&buff[0], SEM_WRITER, 0, IPC_NOWAIT); addtobuff(&buff[1], SEM_SYNC, 0, IPC_NOWAIT); addtobuff(&buff[2], SEM_WRITER, +1, SEM_UNDO); semop(semid, buff, 3); if (errno == EAGAIN) { fprintf(stderr, "\n Writer already exists.\n"); exit(EXIT_FAILURE); } addtobuff(&buff[0], SEM_READER, -1, 0); addtobuff(&buff[1], SEM_READER, +1, 0); addtobuff(&buff[2], SEM_SYNC, +1, SEM_UNDO); addtobuff(&buff[3], SEM_EMPTY, +1, SEM_UNDO); semop(semid, buff, 4); addtobuff(&buff[0], SEM_READER, -1, IPC_NOWAIT); addtobuff(&buff[1], SEM_READER, +1, 0); addtobuff(&buff[2], SEM_SYNC, -2, 0); addtobuff(&buff[3], SEM_SYNC, +2, 0); semop(semid, buff, 4); if (errno == EAGAIN) { fprintf(stderr, "\n Sync error\n"); exit(EXIT_FAILURE); } shm_mem= shmat(shmid, NULL, 0); fileid= open(argv[1], O_RDONLY); while (count) { count= read(fileid, shm_mem+4, BUFF_SIZE); *((int*)shm_mem)= count; addtobuff(&buff[0], SEM_EMPTY, -1, 0); semop(semid, buff, 1); addtobuff(&buff[0], SEM_READER, -1, IPC_NOWAIT); addtobuff(&buff[1], SEM_READER, +1, 0); addtobuff(&buff[2], SEM_FULL, 0, 0); addtobuff(&buff[3], SEM_FULL, +1, 0); semop(semid, buff, 4); if (semctl(semid, 4, GETVAL) == 1) { fprintf(stderr, "\n No reader\n"); semunion.array= sems; semctl(semid, 0, SETALL, semunion); exit(EXIT_FAILURE); } } semunion.array= sems; semctl(semid, 0, SETALL, semunion); } shmdt(shm_mem); return 0; }
int main(int argc, char ** argv){ int i,j; pid_t pid; key_t key; int mqdes[N+1]; int somme=0; struct msgbuf msg, msg2; //Creation de toute les files de messages for(i=0; i<N+1; i++){ key = ftok("/tmp",42+i); if((mqdes[i]=msgget(key, 0666 | IPC_CREAT))==-1){ perror("msgget"); exit(EXIT_FAILURE); } } //Creation des fils for(i=0;i<N;i++){ if((pid=fork())==-1){ perror("fork"); exit(EXIT_FAILURE); }else if(pid==0){ srand(time(NULL)+i); msg.mtype=i+1; msg.mtext=(int)((N*(float)rand()/RAND_MAX)+1); printf("Fils %d : Envoie de la valeur %d a son pere\n", i+1, msg.mtext); //On demande au pere de recevoir un certain nombre de messages if(msgsnd(mqdes[N], &msg, sizeof(int),0)==-1){ perror("msgsnd fils"); exit(EXIT_FAILURE); } //On recupere les messages envoyes par le pere for(j=msg.mtext; j>0; j--){ if(msgrcv(mqdes[i], &msg2, sizeof(int),0,0)==-1){ perror("msgrcv fils"); exit(EXIT_FAILURE); } somme+=msg2.mtext; } printf("Fils %d : somme = %d\n", i+1, somme); exit(EXIT_SUCCESS); } } for(i=0;i<N;i++){ //Pour chaque fils on recupere le nombre de messages qu'il veut recevoir if(msgrcv(mqdes[N],&msg2,sizeof(int),0,0)==-1){ perror("msgrcv pere"); exit(EXIT_FAILURE); } msg.mtype=42; printf("Fils %ld veut %d messages \n", msg2.mtype, msg2.mtext); //on ecrit dans la file de message du fils le nombre de messages indique for(j=0; j<msg2.mtext; j++){ msg.mtext = (int)(100*(float)rand()/RAND_MAX); printf("Pere envoie %d a fils %ld\n", msg.mtext, msg2.mtype); if(msgsnd(mqdes[msg2.mtype-1], &msg, sizeof(int),0)==-1){ perror("msgsnd pere"); exit(EXIT_FAILURE); } } } //attente de la fin des fils for(i=0;i<N;i++){ wait(NULL); } //Destruction des files for(i=0; i<N+1; i++){ if(msgctl(mqdes[i], IPC_RMID, 0)==-1){ perror("msgctl"); exit(EXIT_FAILURE); } } return EXIT_SUCCESS; }
/****************************************************************************** * * * Function: zbx_mutex_create_ext * * * * Purpose: Create the mutex * * * * Parameters: mutex - handle of mutex * * name - name of mutex (index for nix system) * * forced - remove mutex if exists (only for nix) * * * * Return value: If the function succeeds, then return SUCCEED, * * FAIL on an error * * * * Author: Eugene Grigorjev * * * * Comments: use alias 'zbx_mutex_create' and 'zbx_mutex_create_force' * * * ******************************************************************************/ int zbx_mutex_create_ext(ZBX_MUTEX *mutex, ZBX_MUTEX_NAME name, unsigned char forced) { #ifdef _WINDOWS if (NULL == (*mutex = CreateMutex(NULL, FALSE, name))) { zbx_error("error on mutex creating: %s", strerror_from_system(GetLastError())); return FAIL; } #else #define ZBX_MAX_ATTEMPTS 10 int attempts = 0, i; key_t sem_key; union semun semopts; struct semid_ds seminfo; if (-1 == (sem_key = ftok(CONFIG_FILE, (int)'z'))) { zbx_error("cannot create IPC key for path '%s', try to create for path '.': %s", CONFIG_FILE, zbx_strerror(errno)); if (-1 == (sem_key = ftok(".", (int)'z'))) { zbx_error("cannot create IPC key for path '.': %s", zbx_strerror(errno)); return FAIL; } } lbl_create: if (-1 != ZBX_SEM_LIST_ID || -1 != (ZBX_SEM_LIST_ID = semget(sem_key, ZBX_MUTEX_COUNT, IPC_CREAT | IPC_EXCL | 0600 /* 0022 */)) ) { /* set default semaphore value */ semopts.val = 1; for (i = 0; ZBX_MUTEX_COUNT > i; i++) { if (-1 == semctl(ZBX_SEM_LIST_ID, i, SETVAL, semopts)) { zbx_error("semaphore [%i] error in semctl(SETVAL): %s", name, zbx_strerror(errno)); return FAIL; } zbx_mutex_lock(&i); /* call semop to update sem_otime */ zbx_mutex_unlock(&i); /* release semaphore */ } } else if (EEXIST == errno) { ZBX_SEM_LIST_ID = semget(sem_key, 0 /* get reference */, 0600 /* 0022 */); if (1 == forced) { if (0 != semctl(ZBX_SEM_LIST_ID, 0, IPC_RMID, 0)) { zbx_error("cannot recreate Zabbix semaphores for IPC key 0x%lx Semaphore ID %ld: %s", sem_key, ZBX_SEM_LIST_ID, zbx_strerror(errno)); exit(EXIT_FAILURE); } /* semaphore is successfully removed */ ZBX_SEM_LIST_ID = -1; if (ZBX_MAX_ATTEMPTS < ++attempts) { zbx_error("cannot recreate Zabbix semaphores for IPC key 0x%lx: too many attempts", sem_key); exit(EXIT_FAILURE); } if ((ZBX_MAX_ATTEMPTS / 2) < attempts) zbx_sleep(1); goto lbl_create; } semopts.buf = &seminfo; /* wait for initialization */ for (i = 0; ZBX_MUTEX_MAX_TRIES > i; i++) { if (-1 == semctl(ZBX_SEM_LIST_ID, 0, IPC_STAT, semopts)) { zbx_error("semaphore [%i] error in semctl(IPC_STAT): %s", name, zbx_strerror(errno)); break; } if (0 != semopts.buf->sem_otime) goto lbl_return; zbx_sleep(1); } zbx_error("semaphore [%i] not initialized", name); return FAIL; } else { zbx_error("cannot create Semaphore: %s", zbx_strerror(errno)); return FAIL; } lbl_return: *mutex = name; mutexes++; #endif /* _WINDOWS */ return SUCCEED; }
int main() { char pathname[] = "ex0.c"; key_t key; struct mybuf { long type; double a; double b; long pid; } myMsgBuf; if((key = ftok(pathname, 0)) < 0) { printf("Couldn't generate key!\n"); exit(-1); } if((msqid = msgget(key, 0666 | IPC_CREAT)) < 0) { printf("Can\'t get msqid\n"); exit(-1); } if((semid = semget(key, 1, 0666 | IPC_CREAT)) < 0) { printf("Can\'t create semaphore\n"); exit(-1); } mysembuf.sem_flg = 0; mysembuf.sem_num = 0; mysembuf.sem_op = N; if(semop(semid, &mysembuf, 1) < 0) { printf("Can`t wait for condition\n"); semctl(semid, IPC_RMID, 0); exit(-1); } size_t size = sizeof(mybuf) - sizeof(long); while(1) { mybuf* myMsgBuf = (mybuf*)calloc(1, sizeof(mybuf)); if(msgrcv(msqid, (struct msgbuf*)myMsgBuf, size, 1, 0) < 0) { printf("Can't receive a message, errno = %d\n", errno); msgctl(msqid, IPC_RMID, (struct msqid_ds*)NULL); exit(-1); } printf("received a message from %ld\n", myMsgBuf->pid); pthread_t thread_id; if(pthread_create(&thread_id, (pthread_attr_t*)NULL, ThreadFunc, (void*)myMsgBuf) < 0) { printf("Can't create a thread!\n"); exit(-1); } } msgctl(msqid, IPC_RMID, (struct msqid_ds*)NULL); semctl(semid, IPC_RMID, 0); return 0; }
void Service() { // Create child process. pid_t pid; pid = fork(); if( pid != 0 ) exit( 0 ); FILE * fp = fopen( PID_FILE, "wb" ); if( fp ) { pid = getpid(); fwrite( &pid, 1, sizeof( pid ), fp ); fclose( fp ); } else { printf( "[Error] 启动数据库服务出错:创建PID文件失败!\n" ); exit( 0 ); } // setup signal callback. signal( SIGTERM, OnBeforeExit ); // Create message queue. key_t key = ftok( MSG_PATH, 'a' ); g_msgId = msgget( key, IPC_CREAT | 0666 ); if( g_msgId == -1 ) { switch( errno ) { case EEXIST : printf( "[Error] 创建消息队列出错:该消息队列已经存在!\n" ); break; case ENOMEM : printf( "[Error] 创建消息队列出错:核心内存不足!\n" ); break; case ENOSPC : printf( "[Error] 创建消息队列出错:超过可建立的消息队列最大数目!\n" ); break; default : printf( "[Error] 创建消息队列出错:系统内部错误!\n" ); break; } Stop(); exit( 0 ); } // Start service if( g_app.start() != 0 ) { Stop(); exit( 0 ); } printf( "[Info] 数据库服务启动成功!\n" ); // Wait for the cmd service message. S_Cmd_Message msg; while( 1 ) { if( msgrcv( g_msgId, &msg, sizeof( msg ) - sizeof( long ), MSG_NUM, MSG_NOERROR ) == -1 ) { switch( errno ) { case EFAULT : g_app.writeServiceLog( "接收消息出错:内存缓冲区地址无效!" ); break; default : g_app.writeServiceLog( "接收消息出错:系统内部错误!" ); break; } continue; } // Handle message. g_app.m_dbConn.execute( msg.szCmd ); } }
int cgiMain(void) { int ret; key_t key; key_t key_cgi; int flag; int shm_id,sem_id, sem_id_cgi; char *shm; // 创建并关联共享内存 key = ftok("./vs_shm",0); key_cgi = ftok("./vs_shm_cgi",0); shm_id = shmget(key,SEGSIZE,0); if(-1 == shm_id) { cgiHeaderContentType("text/html; charset=gb2312"); puts("<html><head><title>share memeroy error</title><h1><font color='red'>create shared memory error</f><h1><html><head>"); return -1; } shm = (char *)shmat(shm_id,0,0); if (-1 == (int)shm) { cgiHeaderContentType("text/html; charset=gb2312"); puts(" attach shared memory error\n"); return -1; } // 创建互斥锁 sem_id = sem_creat(key); // vs程序操作共享内存信号量 sem_id_cgi = sem_creat(key_cgi); // 外部程序cgi操作共享内存信号量 cgiFormInteger("flag", &flag, 1); if(1 == flag){ //getData cgi_rtv_get_action(shm); post_v(sem_id); // 使能vs程序操作共享内存信号量 wait_v(sem_id_cgi); ret = *(int *)shm; if(0 != ret ) { char temp[32]; sprintf(temp,"error is %d\n",ret); cgiHeaderContentType("text/html; charset=gb2312"); puts("<html><head><title>rtv get error</title><h1><font color='red'>wrong username or password</f><h1>"); puts(temp); return -1; } cgi_rtv_puts(shm); } else if(0 == flag){ cgi_rtv_set_action(shm); post_v(sem_id); // 使能vs程序操作共享内存信号量 wait_v(sem_id_cgi); ret = *(int *)shm; if(0 != ret ) { char temp[32]; sprintf(temp,"error is %d\n",ret); cgiHeaderContentType("text/html; charset=gb2312"); puts("<html><head><title>login error</title><h1><font color='red'>wrong username or password</f><h1>"); puts(temp); return -1; } cgi_rtv_puts(shm); } shmdt(shm); return 0; }
/*********************************************************** * Function: // main * Description: // 主函数 ***********************************************************/ int main( void ) { int flag1, flag2, key, i, init_ok, tmperrno; struct semid_ds sem_info; struct seminfo sem_info2; union semun arg; //union semun: 请参考附录2 struct sembuf askfor_res, free_res; flag1 = IPC_CREAT | IPC_EXCL | 00666; flag2 = IPC_CREAT | 00666; key = ftok( SEM_PATH, 'a' ); //error handling for ftok here; init_ok = 0; semid = semget( key, 1, flag1 ); //create a semaphore set that only includes one semphore. if( semid < 0 ) { tmperrno = errno; perror( "semget" ); //errno is undefined after a successful library call( including perror call) //so it is saved in tmperrno. if( tmperrno == EEXIST ) { semid = semget( key, 1, flag2 ); //flag2 只包含了IPC_CREAT标志, 参数nsems(这里为1)必须与原来的信号灯数目一致 arg.buf = &sem_info; for( i = 0; i < max_tries; i++ ) { if( semctl( semid, 0, IPC_STAT, arg ) == -1 ) { perror( "semctl error" ); i = max_tries; }else { if( arg.buf->sem_otime != 0 ) { i = max_tries; init_ok = 1; }else { sleep( 1 ); } } } if( !init_ok ) // do some initializing, here we assume that the first process that creates the sem // will finish initialize the sem and run semop in max_tries*1 seconds. else it will // not run semop any more. { arg.val = 1; if( semctl( semid, 0, SETVAL, arg ) == -1 ) { perror( "semctl setval error" ); } } }else { perror( "semget error, process exit" ); exit( 1 ); } }else //semid>=0; do some initializing { arg.val = 1; if( semctl( semid, 0, SETVAL, arg ) == -1 ) { perror( "semctl setval error" ); } } //get some information about the semaphore and the limit of semaphore in redhat8.0 arg.buf = &sem_info; if( semctl( semid, 0, IPC_STAT, arg ) == -1 ) { perror( "semctl IPC STAT" ); } printf( "owner's uid is %d\n", arg.buf->sem_perm.uid ); printf( "owner's gid is %d\n", arg.buf->sem_perm.gid ); printf( "creater's uid is %d\n", arg.buf->sem_perm.cuid ); printf( "creater's gid is %d\n", arg.buf->sem_perm.cgid ); arg.__buf = &sem_info2; if( semctl( semid, 0, IPC_INFO, arg ) == -1 ) { perror( "semctl IPC_INFO" ); } printf( "the number of entries in semaphore map is %d \n", arg.__buf->semmap ); printf( "max number of semaphore identifiers is %d \n", arg.__buf->semmni ); printf( "mas number of semaphores in system is %d \n", arg.__buf->semmns ); printf( "the number of undo structures system wide is %d \n", arg.__buf->semmnu ); printf( "max number of semaphores per semid is %d \n", arg.__buf->semmsl ); printf( "max number of ops per semop call is %d \n", arg.__buf->semopm ); printf( "max number of undo entries per process is %d \n", arg.__buf->semume ); printf( "the sizeof of struct sem_undo is %d \n", arg.__buf->semusz ); printf( "the maximum semaphore value is %d \n", arg.__buf->semvmx ); //now ask for available resource: askfor_res.sem_num = 0; askfor_res.sem_op = -1; askfor_res.sem_flg = SEM_UNDO; if( semop( semid, &askfor_res, 1 ) == -1 ) //ask for resource { perror( "semop error" ); } sleep( 3 ); //do some handling on the sharing resource here, just sleep on it 3 seconds printf( "now free the resource\n" ); //now free resource free_res.sem_num = 0; free_res.sem_op = 1; free_res.sem_flg = SEM_UNDO; if( semop( semid, &free_res, 1 ) == -1 ) //free the resource. { if( errno == EIDRM ) { printf( "the semaphore set was removed\n" ); } } //you can comment out the codes below to compile a different version: if( semctl( semid, 0, IPC_RMID ) == -1 ) { perror( "semctl IPC_RMID" ); } else { printf( "remove sem ok\n" ); } return 0; }
/** * tworzy plik kolejki o nazwie wynikajacej z unikalnej nazwy uzyszkodnika * (dzieki temu nie nalezy przekazywac id kolejki (otworzyc kolejke z pliku mozna) * - ale i tak to robie) * otwiera kolejke w tym pliku */ int createQueue(char* name) { close(open(name,O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP)); int queue_id= msgget(ftok(name,1), IPC_CREAT | S_IRUSR | S_IWUSR | S_IWGRP); return queue_id; }
int main(int argc, char *argv[]) { key_t key; int msgqueue_id; struct mymsgbuf qbuf; /* Create unique key via call to ftok() */ key = ftok(".", 'm'); if ((msgqueue_id = msgget(key, IPC_CREAT | 0660)) == -1) { perror("msgget"); exit(1); } int c = 0; int i = 0; client_type = read_type(msgqueue_id, &qbuf, TYPE_TYPE, 0); char temp[2]; sprintf(temp, "%d", client_type + 1); send_message(msgqueue_id, (struct mymsgbuf *) &qbuf, TYPE_TYPE, temp); char buf[MAX_SEND_SIZE]; pid_t pid = fork(); while (c != ESC_CODE) { if (pid == 0) { struct mymsgbuf inpbuf; read_message(msgqueue_id, &inpbuf, client_type, 0); } else { c = getchar(); if (i < MAX_SEND_SIZE) { buf[i++] = c; } else { printf("Very big message!\n"); i = 0; continue; } if (c == RETURN_CODE) { if (i > 1) { buf[i] = 0; struct mymsgbuf outbuf; send_message(msgqueue_id, (struct mymsgbuf *) &outbuf, MESSAGE_TYPE, buf); } i = 0; } } } printf("\n"); return (0); }
void serveLoop(ConnectsServer *connectDesc) { ExternalDevice *dev; char accept_text[10]; int size, base_addr, block_size; ARMMemBlock *mem_block; ARMMemNode *mem_node; ARMProc *proc; char pathname[108]; RegisterDevice reg; char *memory; proc = (ARMProc *)connectDesc->proc; while(connectDesc->running) { dev = malloc(sizeof(ExternalDevice)); dev->tellWritten = &tellWritten; dev->lock = &lockExternalDevice; dev->unlock = &unlockExternalDevice; size = sizeof(dev->remote); if((dev->socket = accept(connectDesc->socket, (struct sockaddr *)&dev->remote, &size)) == -1) { perror("accept"); exit(1); } size = recv(dev->socket, ®, sizeof(RegisterDevice), 0); if(size < 0) { perror("recv"); exit(1); } else if(size == 0) { printf("No se recibio nada"); exit(1); } strcpy(accept_text, "accept"); if(send(dev->socket, accept_text, strlen(accept_text), 0) < 0) { perror("send"); exit(1); } strcpy(dev->name, reg.name); sprintf(pathname, "/tmp/%s.ipc", dev->name); if((dev->key = ftok(pathname, 'A')) == -1) { perror("ftok"); exit(1); } if((dev->semid = semget(dev->key, 1, 0666)) == -1) { perror("semget"); exit(1); } if((dev->shmid = shmget(dev->key, reg.size, 0666)) == -1) { perror("shmget"); exit(1); } if((memory = shmat(dev->shmid, NULL, 0)) == (char *)-1) { perror("shmat"); exit(1); } mem_block = new_mem_block_shm(reg.base_addr, reg.size, memory); mem_block->device = dev; mem_node = new_mem_node(mem_block); add_mem_block(proc->memory->root, mem_node); } }
int ketama_roll( ketama_continuum* contptr, char* filename ) { strcpy( k_error, "" ); key_t key; int shmid; int *data; int sem_set_id; // setlogmask( LOG_UPTO ( LOG_NOTICE | LOG_ERR | LOG_INFO ) ); // openlog( "ketama", LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL1 ); key = ftok( filename, 'R' ); if ( key == -1 ) { sprintf( k_error, "Invalid filename specified: %s", filename ); return 0; } *contptr = malloc( sizeof( continuum ) ); (*contptr)->numpoints = 0; (*contptr)->array = 0; (*contptr)->modtime = 0; sem_set_id = ketama_sem_init( key ); int sanity = 0; while ( semctl( sem_set_id, 0, GETVAL, 0 ) == 2 ) { // wait for the continuum creator to finish, but don't block others usleep( 5 ); // if we are waiting for > 1 second, take drastic action: if(++sanity > 1000000) { usleep( rand()%50000 ); ketama_sem_unlock( sem_set_id ); break; } } time_t modtime = file_modtime( filename ); time_t* fmodtime = 0; while ( !fmodtime || modtime != *fmodtime ) { shmid = shmget( key, MC_SHMSIZE, 0 ); // read only attempt. data = shmat( shmid, (void *)0, SHM_RDONLY ); if ( data == (void *)(-1) || (*contptr)->modtime != 0 ) { ketama_sem_lock( sem_set_id ); // if ( (*contptr)->modtime == 0 ) // syslog( LOG_INFO, "Shared memory empty, creating and populating...\n" ); // else // syslog( LOG_INFO, "Server definitions changed, reloading...\n" ); if ( !ketama_create_continuum( key, filename ) ) { // strcpy( k_error, "Ketama_create_continuum() failed!" ); ketama_sem_unlock( sem_set_id ); return 0; } /* else syslog( LOG_INFO, "ketama_create_continuum() successfully finished.\n" );*/ shmid = shmget( key, MC_SHMSIZE, 0 ); // read only attempt. data = shmat( shmid, (void *)0, SHM_RDONLY ); ketama_sem_unlock( sem_set_id ); } if ( data == (void *)(-1) ) { strcpy( k_error, "Failed miserably to get pointer to shmemdata!" ); return 0; } (*contptr)->numpoints = *data; (*contptr)->modtime = ++data; (*contptr)->array = data + sizeof( void* ); fmodtime = (time_t*)( (*contptr)->modtime ); } return 1; }
int main() { key_t key; int shmid, semid, msqid; char *shm; char data[] = "this is server"; struct shmid_ds buf1; /*用于删除共享内存*/ struct msqid_ds buf2; /*用于删除消息队列*/ struct msg_form msg; /*消息队列用于通知对方更新了共享内存*/ // 获取key值 if((key = ftok(".", 'z')) < 0) { perror("ftok error"); exit(1); } // 创建共享内存 if((shmid = shmget(key, 1024, IPC_CREAT|0666)) == -1) { perror("Create Shared Memory Error"); exit(1); } // 连接共享内存 shm = (char*)shmat(shmid, 0, 0); if((int)shm == -1) { perror("Attach Shared Memory Error"); exit(1); } // 创建消息队列 if ((msqid = msgget(key, IPC_CREAT|0777)) == -1) { perror("msgget error"); exit(1); } // 创建信号量 semid = creat_sem(key); // 读数据 while(1) { msgrcv(msqid, &msg, 1, 888, 0); /*读取类型为888的消息*/ if(msg.mtext == 'q') /*quit - 跳出循环*/ break; if(msg.mtext == 'r') /*read - 读共享内存*/ { sem_p(semid); printf("%s\n",shm); sem_v(semid); } } // 断开连接 shmdt(shm); /*删除共享内存、消息队列、信号量*/ shmctl(shmid, IPC_RMID, &buf1); msgctl(msqid, IPC_RMID, &buf2); del_sem(semid); return 0; }
void init() { key_t key; key=ftok(".", 'S'); sem_id = semget(key, 2, 0644|IPC_CREAT); }
int main(int ac, char *av[]) { int status = 0; char* logfname = 0; /// Data directory, conffile paths may be relative const char* datadir; int interval = DEFAULT_INTERVAL; prod_spec spec; prod_class_t clss; int toffset = TOFFSET_NONE; int loggingToStdErr = 0; unsigned queue_size = 5000; const char* progname = basename(av[0]); unsigned logopts = LOG_CONS|LOG_PID; /* * Setup default logging before anything else. */ (void)log_init(progname); const char* pqfname = getQueuePath(); spec.feedtype = DEFAULT_FEEDTYPE; spec.pattern = DEFAULT_PATTERN; if(set_timestamp(&clss.from)) /* corrected by toffset below */ { int errnum = errno; log_error("Couldn't set timestamp: %s", strerror(errnum)); exit(EXIT_FAILURE); /*NOTREACHED*/ } clss.to = TS_ENDT; clss.psa.psa_len = 1; clss.psa.psa_val = &spec; /* * deal with the command line, set options */ { extern int optind; extern int opterr; extern char *optarg; int ch; int fterr; opterr = 1; while ((ch = getopt(ac, av, "vxel:d:f:q:o:p:i:t:")) != EOF) { switch (ch) { case 'v': if (!log_is_enabled_info) (void)log_set_level(LOG_LEVEL_INFO); break; case 'x': (void)log_set_level(LOG_LEVEL_DEBUG); break; case 'e': key = ftok("/etc/rc.d/rc.local",'R'); semkey = ftok("/etc/rc.d/rc.local",'e'); shmid = shmget(key, sizeof(edex_message) * queue_size, 0666 | IPC_CREAT); semid = semget(semkey, 2, 0666 | IPC_CREAT); break; case 'l': logfname = optarg; (void)log_set_destination(logfname); break; case 'd': setPqactDataDirPath(optarg); break; case 'f': fterr = strfeedtypet(optarg, &spec.feedtype); if(fterr != FEEDTYPE_OK) { log_error("Bad feedtype \"%s\", %s\n", optarg, strfeederr(fterr)); usage(progname); } break; case 'q': pqfname = optarg; break; case 'o': toffset = atoi(optarg); if(toffset == 0 && *optarg != '0') { log_error("invalid offset %s\n", optarg); usage(progname); } break; case 'i': interval = atoi(optarg); if(interval == 0 && *optarg != '0') { log_error("invalid interval %s\n", optarg); usage(progname); } break; case 't': pipe_timeo = atoi(optarg); if(pipe_timeo == 0 && *optarg != 0) { log_error("invalid pipe_timeo %s", optarg); usage(progname); } break; case 'p': spec.pattern = optarg; break; default: usage(progname); break; } } conffilename = getPqactConfigPath(); datadir = getPqactDataDirPath(); { int numOperands = ac - optind; if (1 < numOperands) { log_error("Too many operands"); usage(progname); } else if (1 == numOperands) { conffilename = av[optind]; } } } setQueuePath(pqfname); log_notice("Starting Up"); if ('/' != conffilename[0]) { /* * The pathname of the configuration-file is relative. Convert it * to absolute so that it can be (re)read even if the current * working directory changes. */ #ifdef PATH_MAX char buf[PATH_MAX]; /* includes NUL */ #else char buf[_POSIX_PATH_MAX]; /* includes NUL */ #endif if (getcwd(buf, sizeof(buf)) == NULL) { log_syserr("Couldn't get current working directory"); exit(EXIT_FAILURE); } (void)strncat(buf, "/", sizeof(buf)-strlen(buf)-1); (void)strncat(buf, conffilename, sizeof(buf)-strlen(buf)-1); conffilename = strdup(buf); if (conffilename == NULL) { log_syserr("Couldn't duplicate string \"%s\"", buf); exit(EXIT_FAILURE); } } /* * Initialize the previous-state module for this process. */ if (stateInit(conffilename) < 0) { log_error("Couldn't initialize previous-state module"); exit(EXIT_FAILURE); /*NOTREACHED*/ } /* * Configure the standard I/O streams for execution of child processes. */ if (configure_stdio_file_descriptors()) { log_error("Couldn't configure standard I/O streams for execution " "of child processes"); exit(EXIT_FAILURE); } /* * Inform the "filel" module about the number of available file * descriptors. File descriptors are reserved for stdin, stdout, * stderr, the product-queue, the configuration-file, and (possibly) * logging. */ if (0 != set_avail_fd_count(openMax() - 6)) { log_error("Couldn't set number of available file-descriptors"); log_notice("Exiting"); exit(EXIT_FAILURE); /*NOTREACHED*/ } /* * Inform the "filel" module of the shared memory segment */ if (shmid != -1 && semid != -1) { set_shared_space(shmid, semid, queue_size); } /* * Compile the pattern. */ if (re_isPathological(spec.pattern)) { log_error("Adjusting pathological regular-expression: \"%s\"", spec.pattern); re_vetSpec(spec.pattern); } status = regcomp(&spec.rgx, spec.pattern, REG_EXTENDED|REG_NOSUB); if(status != 0) { log_error("Can't compile regular expression \"%s\"", spec.pattern); log_notice("Exiting"); exit(EXIT_FAILURE); /*NOTREACHED*/ } /* * register exit handler */ if(atexit(cleanup) != 0) { log_syserr("atexit"); log_notice("Exiting"); exit(EXIT_FAILURE); /*NOTREACHED*/ } /* * set up signal handlers */ set_sigactions(); /* * Read in (compile) the configuration file. We do this first so * its syntax may be checked without opening a product queue. */ if ((status = readPatFile(conffilename)) < 0) { exit(EXIT_FAILURE); /*NOTREACHED*/ } else if (status == 0) { log_notice("Configuration-file \"%s\" has no entries. " "You should probably not start this program instead.", conffilename); } /* * Open the product queue */ status = pq_open(pqfname, PQ_READONLY, &pq); if(status) { if (PQ_CORRUPT == status) { log_error("The product-queue \"%s\" is inconsistent\n", pqfname); } else { log_error("pq_open failed: %s: %s\n", pqfname, strerror(status)); } exit(EXIT_FAILURE); /*NOTREACHED*/ } if(toffset != TOFFSET_NONE) { /* * Filter and queue position set by "toffset". */ clss.from.tv_sec -= toffset; pq_cset(pq, &clss.from); } else { bool startAtTailEnd = true; timestampt insertTime; clss.from = TS_ZERO; /* * Try getting the insertion-time of the last, * successfully-processed data-product from the previous session. */ status = stateRead(&insertTime); if (status) { log_warning("Couldn't get insertion-time of last-processed " "data-product from previous session"); } else { timestampt now; (void)set_timestamp(&now); if (tvCmp(now, insertTime, <)) { log_warning("Time of last-processed data-product from previous " "session is in the future"); } else { char buf[80]; (void)strftime(buf, sizeof(buf), "%Y-%m-%d %T", gmtime(&insertTime.tv_sec)); log_notice("Starting from insertion-time %s.%06lu UTC", buf, (unsigned long)insertTime.tv_usec); pq_cset(pq, &insertTime); startAtTailEnd = false; } } if (startAtTailEnd) { log_notice("Starting at tail-end of product-queue"); (void)pq_last(pq, &clss, NULL); } }