void execSimpleCmd(){ SimpleCmd *cmd = handleSimpleCmd(0, strlen(inputBuff)); int i; pid_t pid; int pipeIn, pipeOut; if(exists(cmd->args[0])){ //命令存在 if((pid = fork()) < 0){ perror("fork failed"); return; } if(pid == 0){ //子进程 if(cmd->isBack){ //若是后台运行命令,等待父进程增加作业 //printf("& !!\n"); signal(SIGUSR1, setGoon); //收到信号,setGoon函数将goon置1,以跳出下面的循环 while(goon == 0) ; //等待父进程SIGUSR1信号,表示作业已加到链表中 goon = 0; //置0,为下一命令做准备 printf("[%d]\t%s\t\t%s\n", getpid(), RUNNING, inputBuff); kill(getppid(), SIGUSR1); } if(cmd->input != NULL){ //存在输入重定向 if((pipeIn = open(cmd->input, O_RDONLY, S_IRUSR|S_IWUSR)) == -1){ printf("不能打开文件 %s!\n", cmd->input); return; } if(dup2(pipeIn, 0) == -1){ printf("重定向标准输入错误!\n"); return; } } if(cmd->output != NULL){ //存在输出重定向 if((pipeOut = open(cmd->output, O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR)) == -1){ printf("不能打开文件 %s!\n", cmd->output); return ; } if(dup2(pipeOut, 1) == -1){ printf("重定向标准输出错误!\n"); return; } } signal(SIGTSTP, ctrl_Z); //设置signal信号,为下一次按下组合键Ctrl+Z做准备 signal(SIGINT,ctrl_C); if(execv(cmdBuff, cmd->args) < 0){ //执行命令 printf("execv failed!\n"); return; } } else{ //父进程 if(cmd ->isBack){ //后台命令 fgPid = 0; //pid置0,为下一命令做准备 addJob(pid); //增加新的作业 sleep(2); kill(pid, SIGUSR1); //子进程发信号,表示作业已加入 //等待子进程输出 signal(SIGUSR1, setGoon); while(goon == 0) ;//printf("fu jin cheng xun huan ing \n"); goon =0; }else{ //非后台命令 fgPid = pid; waitpid(pid, NULL, 0); } } }else{ //命令不存在 printf("找不到命令%s\n", inputBuff); } }
int main(int argc, char *argv[]) { Server server; int r = EXIT_FAILURE, n; if (getppid() != 1) { log_error("This program should be invoked by init only."); return EXIT_FAILURE; } if (argc > 1) { log_error("This program does not take arguments."); return EXIT_FAILURE; } log_set_target(LOG_TARGET_AUTO); log_parse_environment(); log_open(); umask(0022); n = sd_listen_fds(true); if (n < 0) { log_error_errno(r, "Failed to read listening file descriptors from environment: %m"); return EXIT_FAILURE; } if (n <= 0 || n > SERVER_FD_MAX) { log_error("No or too many file descriptors passed."); return EXIT_FAILURE; } if (server_init(&server, (unsigned) n) < 0) return EXIT_FAILURE; log_debug("systemd-initctl running as pid "PID_FMT, getpid_cached()); sd_notify(false, "READY=1\n" "STATUS=Processing requests..."); while (!server.quit) { struct epoll_event event; int k; k = epoll_wait(server.epoll_fd, &event, 1, TIMEOUT_MSEC); if (k < 0) { if (errno == EINTR) continue; log_error_errno(errno, "epoll_wait() failed: %m"); goto fail; } if (k <= 0) break; if (process_event(&server, &event) < 0) goto fail; } r = EXIT_SUCCESS; log_debug("systemd-initctl stopped as pid "PID_FMT, getpid_cached()); fail: sd_notify(false, "STOPPING=1\n" "STATUS=Shutting down..."); server_done(&server); return r; }
int main(int argc, char const *argv[]) { int rval,i; char ser[10]; rval = access("ser.txt",F_OK); signal(SIGINT,getMessage); char *p; printf("My pid is %d\n",getpid()); if(rval!=0) { perror("File read error"); exit(1); } initialize(); int server_pid = atoi(ser); int mypid = getpid(); sprintf(ser,"%d",mypid); pid_t cpid = fork(); if(cpid==0) { //child process to receive the messages mymsgbuf recmsg; int parent_pid = getppid(); signal(SIGINT,SIG_IGN); signal(SIGUSR1,exitChild); int i,rv_bytes; down(semid,PID_ARRAY); for(i=0;i<100;i++) { if(pid[i]==-1) { pid[i]=parent_pid; break; } } up(semid,PID_ARRAY); //receive from msg queue while (1) { rv_bytes = msgrcv(msgqid, &recmsg, MSG_SIZE, parent_pid, 0); if(rv_bytes==-1) { perror("Queue Connection error"); exit(1); } else { printf("--- Received Message:\"%s\"\n",recmsg.data); } } exit(0); } //parent process while(1) { if(strcmp(tmpMsg,".")!=0) { if(strcmp(tmpMsg,"bye")==0) { //the process wants to exit. I need to free up the values. kill(cpid,SIGUSR1);//send the signal to child to exit. rval = 0; down(semid,PID_ARRAY); for(i=0;i<100;i++) { if(pid[i]!=-1) { if(pid[i]==mypid) { pid[i]=-1; } else { rval++; } } } up(semid,PID_ARRAY); if(rval==0) { //none of the children are present p = getlogin(); waitOnSemop(semid,MSG_SEM); strcpy(msg,p); strcat(msg,"/"); strcat(msg,ser); strcat(msg,": "); strcat(msg,"*"); down(semid,MSG_SEM); strcpy(tmpMsg,"."); printf("--- All are gone. Have a nice day\n"); exit(0); //send this message } else { printf("--- I am going. Have a nice chat\n"); exit(0); } } else { p = getlogin(); waitOnSemop(semid,MSG_SEM); strcpy(msg,p); strcat(msg,"/"); strcat(msg,ser); strcat(msg,": "); strcat(msg,tmpMsg); down(semid,MSG_SEM); strcpy(tmpMsg,"."); } } else { p = getlogin(); waitOnSemop(semid,MSG_SEM); if(strcmp(tmpMsg,".")==0) { strcpy(msg,p); strcat(msg,"/"); strcat(msg,ser); strcat(msg,": "); strcat(msg,tmpMsg); } down(semid,MSG_SEM); } } return 0; }
void GraphViewer::initialize(int width, int height, bool dynamic, int port_n) { this->width = width; this->height = height; this->isDynamic = dynamic; string command = "java -jar GraphViewerController.jar"; std::stringstream ss; ss << port_n; string port_string = ss.str(); command += " --port "; command += port_string; #ifdef linux if (!(procId = fork())) { system(command.c_str()); kill(getppid(), SIGINT); exit(0); } else { usleep(2000000); con = new Connection(port_n); char buff[200]; sprintf(buff, "newGraph %d %d %s\n", width, height, (dynamic?"true":"false")); string str(buff); con->sendMsg(str); } #else STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); LPSTR command_lpstr = const_cast<char *>(command.c_str()); if( !CreateProcess( NULL, // No module name (use command line) command_lpstr, // Command line NULL, // Process handle not inheritable NULL, // Thread handle not inheritable FALSE, // Set handle inheritance to FALSE 0, // No creation flags NULL, // Use parent's environment block NULL, // Use parent's starting directory &si, // Pointer to STARTUPINFO structure &pi ) // Pointer to PROCESS_INFORMATION structure ) { printf( "CreateProcess failed (%d).\n", GetLastError() ); return; } // Close process and thread handles. CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); Sleep(2000); con = new Connection(port_n); char buff[200]; sprintf(buff, "newGraph %d %d %s\n", width, height, (dynamic?"true":"false")); string str(buff); con->sendMsg(str); #endif }
static KMETHOD System_getppid(KonohaContext *kctx, KonohaStack *sfp) { KReturnUnboxValue(getppid()); }
int _init(void) { int rc; /* initialize the DosLinuxStructure to zero */ memset(&DosLinuxStruct, 0, sizeof(DOSLINUXSTRUCT)); /* OS/2 processes support */ DosLinuxStruct.pib.pib_ulpid = getpid(); DosLinuxStruct.pib.pib_ulppid = getppid(); DosLinuxStruct.pib.pib_hmte = 0; DosLinuxStruct.pib.pib_pchcmd = NULL; DosLinuxStruct.pib.pib_pchenv = *__environ; DosLinuxStruct.pib.pib_flstatus = 0; DosLinuxStruct.pib.pib_ultype = 2; /* ML_WINDOW_PROC_TYPE */ /* thread specific memory support */ rc = pthread_key_create(&DosLinuxStruct.thrdKey, NULL); if (rc) { syslog(LOG_USER | LOG_ERR, "OS2Linux: Error creating thread specific memory key.\n"); exit(12); } /* thread specific TIB support */ rc = pthread_key_create(&DosLinuxStruct.thrdTIBKey, NULL); if (rc) { syslog(LOG_USER | LOG_ERR, "OS2Linux: Error creating thread specific TIB key.\n"); exit(12); } /* OS/2 process critical section mutex semaphore */ rc = pthread_mutex_init(&DosLinuxStruct.critSecMutex, NULL ); if (rc) { syslog(LOG_USER | LOG_ERR, "OS2Linux: Error creating thread critical section mutex semaphore.\n" "OS2Linux: The errno was %d.\n", errno); exit(12); } /* system-wide mutex semaphore for this library */ /* do NOT use the OS/2 APIs here! */ DosLinuxStruct.SysMutexSem = sem_open(SYSMUTEXSEMNAME, (O_CREAT | O_EXCL), (S_IRWXU | S_IRWXG), 0); if (DosLinuxStruct.SysMutexSem == SEM_FAILED ) { if (errno == EEXIST) { DosLinuxStruct.SysMutexSem = sem_open(SYSMUTEXSEMNAME, 0);; if (DosLinuxStruct.SysMutexSem == SEM_FAILED ) { syslog(LOG_USER | LOG_ERR, "OS2Linux: Error opening the system-wide mutex semaphore.\n" "OS2Linux: The errno was %d.\n", errno); exit(12); } } else { syslog(LOG_USER | LOG_ERR, "OS2Linux: Error creating the system-wide mutex semaphore.\n" "OS2Linux: The errno was %d.\n", errno); exit(12); } } sem_post(DosLinuxStruct.SysMutexSem); /* termination code to use for this program */ DosLinuxStruct.termcode = TC_EXIT; /* fix this! */ /* support for an array of OS/2 asyncronous timers */ DosLinuxStruct.asyncTimerHandler[0] = DosAsyncTimerHandler_0; DosLinuxStruct.asyncTimerHandler[1] = DosAsyncTimerHandler_1; DosLinuxStruct.asyncTimerHandler[2] = DosAsyncTimerHandler_2; DosLinuxStruct.asyncTimerHandler[3] = DosAsyncTimerHandler_3; DosLinuxStruct.asyncTimerHandler[4] = DosAsyncTimerHandler_4; DosLinuxStruct.asyncTimerHandler[5] = DosAsyncTimerHandler_5; DosLinuxStruct.asyncTimerHandler[6] = DosAsyncTimerHandler_6; DosLinuxStruct.asyncTimerHandler[7] = DosAsyncTimerHandler_7; DosLinuxStruct.asyncTimerHandler[8] = DosAsyncTimerHandler_8; DosLinuxStruct.asyncTimerHandler[9] = DosAsyncTimerHandler_9; /* establish the program errno for the client program */ errno = 0; return 0; }
int main( int argc, char** argv) { float t1[N]; float t2[M]; for (int i = 0; i<N; i++) t1[i]= 3*i + 2.0; for (int i=0; i <M; i++) t2[i]= i*i + 7.0; int pid; if ((pid= fork())==-1) perror("could not fork \n"); else if (pid == 0)//child process { cpu_set_t set, setp, get; int r, r1; CPU_ZERO(&set); CPU_ZERO(&setp); CPU_SET(0, &set); CPU_SET(3, &setp); //CPU_SET(2, &setp); if ((r=sched_setaffinity(getpid(), sizeof(cpu_set_t), &set))==-1) perror("could not set affinity"); if ((r=sched_setaffinity(getppid(), sizeof(cpu_set_t), &setp))==-1) perror("could not set affinity"); kill(getppid(), SIGUSR1); if ((r1=sched_getaffinity(getpid(), sizeof(cpu_set_t), &get))==-1) perror("could not get affinity"); int ncpu=0; ncpu = CPU_COUNT(&get); printf("from child, number of cpu=%d,\n", ncpu); clock_t start=clock(), diff; for(int i=0;;i++) { t1[i%N]+= 3.0; diff= clock() - start; int msec = diff * 1000 / CLOCKS_PER_SEC; //printf("Elapsed time = %d\n", msec); if (msec > 2000) { start = clock(); printf("from child, t1[0]= %f\n", t1[0]); } } } else //parent process { signal(SIGUSR1,myHandler); clock_t start=clock(), diff; cpu_set_t set, get; int r, r2; CPU_ZERO(&set); //CPU_SET(0, &set); /*CPU_SET(2, &set); if (r=sched_setaffinity(getpid(), sizeof(cpu_set_t), &set)==-1) perror("could not get affinity");*/ pause(); if ((r2=sched_getaffinity(getpid(), sizeof(cpu_set_t), &get))==-1) perror("could not get affinity"); int ncpu=0; ncpu = CPU_COUNT(&get); printf("from parent, number of cpu=%d,\n", ncpu); for(int i=0;;i++) { t2[i%N]-= 4.0; diff= clock() - start; int msec = diff * 1000 / CLOCKS_PER_SEC; if (msec > 2000) { start = clock(); printf("from parent, t2[0]= %f\n", t2[0]); } } } return 0; }
int main() { printf ("I am process %ld.\n", (long) getpid()); printf ("My parent is %ld.\n", (long) getppid()); return 0; }
void kore_accesslog(struct http_request *req) { struct timespec ts; struct tm *tm; u_int64_t now; struct kore_alog_header *hdr; size_t avail; time_t curtime; int len, attempts; char addr[INET6_ADDRSTRLEN]; const char *ptr, *method, *cn, *referer; switch (req->method) { case HTTP_METHOD_GET: method = "GET"; break; case HTTP_METHOD_POST: method = "POST"; break; case HTTP_METHOD_PUT: method = "PUT"; break; case HTTP_METHOD_DELETE: method = "DELETE"; break; case HTTP_METHOD_HEAD: method = "HEAD"; break; case HTTP_METHOD_PATCH: method = "PATCH"; break; default: method = "UNKNOWN"; break; } if (req->referer != NULL) referer = req->referer; else referer = "-"; cn = "-"; #if !defined(KORE_NO_TLS) if (req->owner->cert != NULL) { if (X509_GET_CN(req->owner->cert, cnbuf, sizeof(cnbuf)) != -1) cn = cnbuf; } #endif switch (req->owner->family) { case AF_INET: ptr = inet_ntop(req->owner->family, &(req->owner->addr.ipv4.sin_addr), addr, sizeof(addr)); break; case AF_INET6: ptr = inet_ntop(req->owner->family, &(req->owner->addr.ipv6.sin6_addr), addr, sizeof(addr)); break; case AF_UNIX: ptr = NULL; break; default: fatal("unknown family %d", req->owner->family); } if (ptr == NULL) { addr[0] = '-'; addr[1] = '\0'; } now = kore_time_ms(); if ((now - time_cache) >= 1000) { time(&curtime); tm = localtime(&curtime); (void)strftime(tbuf, sizeof(tbuf), "%d/%b/%Y:%H:%M:%S %z", tm); time_cache = now; } attempts = 0; ts.tv_sec = 0; ts.tv_nsec = 1000000; for (;;) { if (attempts++ > 1000) { if (getppid() == 1) { if (kill(worker->pid, SIGQUIT) == -1) fatal("failed to shutdown"); return; } attempts = 0; } accesslog_lock(worker); avail = KORE_ACCESSLOG_BUFLEN - worker->lb.offset; if (avail < sizeof(*hdr) + LOG_ENTRY_MINSIZE_GUESS) { accesslog_unlock(worker); nanosleep(&ts, NULL); continue; } hdr = (struct kore_alog_header *) (worker->lb.buf + worker->lb.offset); worker->lb.offset += sizeof(*hdr); len = snprintf(worker->lb.buf + worker->lb.offset, avail, "%s - %s [%s] \"%s %s HTTP/1.1\" %d %zu \"%s\" \"%s\"\n", addr, cn, tbuf, method, req->path, req->status, req->content_length, referer, req->agent); if (len == -1) fatal("failed to create log entry"); if ((size_t)len >= avail) { worker->lb.offset -= sizeof(*hdr); accesslog_unlock(worker); nanosleep(&ts, NULL); continue; } if ((size_t)len > USHRT_MAX) { kore_log(LOG_WARNING, "log entry length exceeds limit (%d)", len); worker->lb.offset -= sizeof(*hdr); break; } hdr->loglen = len; hdr->domain = req->hdlr->dom->id; worker->lb.offset += (size_t)len; break; } accesslog_unlock(worker); }
int main(void){ int status, id, j; //Cria as estruturas de IPC e o canal de comunicação POSIX mqd_t msgq_id; unsigned int sender; char msgcontent[MSG_SIZE]; char msgcontentRCV[MAX_MSG_SIZE]; struct mq_attr msgq_attr; int msgsz; msgq_id = mq_open(MSGQOBJ_NAME, O_RDWR | O_CREAT | O_EXCL, S_IRWXU | S_IRWXG, NULL); if (msgq_id < 0) { msgq_id = mq_open(MSGQOBJ_NAME, O_RDWR); if(msgq_id < 0){ perror("mq_open"); exit(1); } } //Insira um comando para pegar o PID do processo corrente e mostre na tela da console. printf("Processo Corrente - %i\n\n", getpid()); id = fork(); if (id != 0){ //Faça com que o processo pai execute este trecho de código //Mostre na console o PID do processo pai e do processo filho printf("Sou o processo Pai de PID %i e tenho o processo Filho de PID %i\n", getpid(), id); //Monte uma mensagem e a envie para o processo filho strcpy(msgcontent, "Olá processo Filho!"); mq_send(msgq_id, msgcontent, strlen(msgcontent)+1, 10); //Mostre na tela o texto da mensagem enviada printf("Mensagem enviada ao Filho: %s\n", msgcontent); //Aguarde a resposta do processo filho wait(&status); msgsz = mq_receive(msgq_id, msgcontentRCV, MAX_MSG_SIZE, &sender); if (msgsz == -1) { perror("mq_receive()"); exit(1); } //Mostre na tela o texto recebido do processo filho printf("\n1a Mensagem enviada pelo filho - %s\n", msgcontentRCV); //Aguarde mensagem do filho e mostre o texto recebido msgsz = mq_receive(msgq_id, msgcontentRCV, MAX_MSG_SIZE, &sender); if (msgsz == -1) { perror("mq_receive()"); exit(1); } printf("2a Mensagem enviada pelo filho - %s\n", msgcontentRCV); //Aguarde o término do processo filho wait(&status); mq_close(msgq_id); //Informe na tela que o filho terminou e que o processo pai também vai encerrar printf("O Processo Filho terminou e o pai também se encerrará.\n"); exit(0); }else{ //Faça com que o processo filho execute este trecho de código //Mostre na tela o PID do processo corrente e do processo pai printf("Sou o processo de PID %i e tenho o Processo Pai de PID %i\n", getpid(), getppid()); //Aguarde a mensagem do processo pai e ao receber mostre o texto na tela mq_getattr(msgq_id, &msgq_attr); msgsz = mq_receive(msgq_id, msgcontentRCV, MAX_MSG_SIZE, &sender); if (msgsz == -1) { perror("mq_receive()"); exit(1); } printf("Mensagem enviada pelo pai - %s\n", msgcontentRCV); //Envie uma mensagem resposta ao pai strcpy(msgcontent, "Olá processo Pai!"); mq_send(msgq_id, msgcontent, strlen(msgcontent)+1, 10); //Execute o comando “for” abaixo for (j = 0; j <= 10000; j++); //Envie mensagem ao processo pai com o valor final de “j” sprintf(msgcontent, "j=%i", j); mq_send(msgq_id, msgcontent, strlen(msgcontent)+1, 10); //Execute o comando abaixo e responda às perguntas printf("\n"); execl("/bin/ls", "ls", NULL); /* ====================================================================================================================== Responda:O que acontece após este comando? O processo filho executa o comando execl que é criado pelo SO de forma independente. Isso ocorre, pois o ls não é uma instância de Prog1, diferentemente dos processos filho e pai. Sendo assim, esse comando será executado pelo SO de forma dissociada dos demais. Quando a execução do execl() é bem sucedida, o segmento de instruções do processo filho (processo corrente) é substituído pelo segmento do processo que foi chamado pelo execl(), portanto o processo filho não continua em execução. Por sua vez, o processo pai identifica que o processo filho não existe mais e continua sua própria execução. Responda:O que pode acontecer se o comando “execl” falhar? O comando execl() retorna o valor -1, indicando que houve falha na sua execução. Neste caso, o processo filho (processo corrente) retorna sua execução normalmente. ---------------------------------------------------------------------------------------------------------------------- */ mq_close(msgq_id); exit(0); } }
int ShowPid() { printf("%d %d", getpid(), getppid() ); return 1; }
void make_session_key(char *key, char *seed, int mode) { int j, k; struct MD5Context md5c; unsigned char md5key[16], md5key1[16]; char s[1024]; #define ss sizeof(s) s[0] = 0; if (seed != NULL) { bstrncat(s, seed, sizeof(s)); } /* The following creates a seed for the session key generator based on a collection of volatile and environment-specific information unlikely to be vulnerable (as a whole) to an exhaustive search attack. If one of these items isn't available on your machine, replace it with something equivalent or, if you like, just delete it. */ #if defined(HAVE_WIN32) { LARGE_INTEGER li; DWORD length; FILETIME ft; bsnprintf(s + strlen(s), ss, "%lu", (uint32_t)GetCurrentProcessId()); (void)getcwd(s + strlen(s), 256); bsnprintf(s + strlen(s), ss, "%lu", (uint32_t)GetTickCount()); QueryPerformanceCounter(&li); bsnprintf(s + strlen(s), ss, "%lu", (uint32_t)li.LowPart); GetSystemTimeAsFileTime(&ft); bsnprintf(s + strlen(s), ss, "%lu", (uint32_t)ft.dwLowDateTime); bsnprintf(s + strlen(s), ss, "%lu", (uint32_t)ft.dwHighDateTime); length = 256; GetComputerName(s + strlen(s), &length); length = 256; GetUserName(s + strlen(s), &length); } #else bsnprintf(s + strlen(s), ss, "%lu", (uint32_t)getpid()); bsnprintf(s + strlen(s), ss, "%lu", (uint32_t)getppid()); (void)getcwd(s + strlen(s), 256); bsnprintf(s + strlen(s), ss, "%lu", (uint32_t)clock()); bsnprintf(s + strlen(s), ss, "%lu", (uint32_t)time(NULL)); #if defined(Solaris) sysinfo(SI_HW_SERIAL,s + strlen(s), 12); #endif #if defined(HAVE_GETHOSTID) bsnprintf(s + strlen(s), ss, "%lu", (uint32_t) gethostid()); #endif gethostname(s + strlen(s), 256); bsnprintf(s + strlen(s), ss, "%lu", (uint32_t)getuid()); bsnprintf(s + strlen(s), ss, "%lu", (uint32_t)getgid()); #endif MD5Init(&md5c); MD5Update(&md5c, (uint8_t *)s, strlen(s)); MD5Final(md5key, &md5c); bsnprintf(s + strlen(s), ss, "%lu", (uint32_t)((time(NULL) + 65121) ^ 0x375F)); MD5Init(&md5c); MD5Update(&md5c, (uint8_t *)s, strlen(s)); MD5Final(md5key1, &md5c); #define nextrand (md5key[j] ^ md5key1[j]) if (mode) { for (j = k = 0; j < 16; j++) { unsigned char rb = nextrand; #define Rad16(x) ((x) + 'A') key[k++] = Rad16((rb >> 4) & 0xF); key[k++] = Rad16(rb & 0xF); #undef Rad16 if (j & 1) { key[k++] = '-'; } } key[--k] = 0; } else { for (j = 0; j < 16; j++) {
void daemonize(void) { int i; char str[10]; if (getppid()==1) { return; /* already a daemon */ } i = (int)fork(); if (i<0) { /* fork error */ perror("Error: fork"); exit(EXIT_FAILURE); } if (i>0) { /* parent exits */ exit(EXIT_SUCCESS); } /* child (daemon) continues */ setsid(); /* obtain a new process group */ if (cfg.uselogging) { snprintf(errorstring, 512, "vnStat daemon %s started. (uid:%d gid:%d)", VNSTATVERSION, (int)getuid(), (int)getgid()); if (!printe(PT_Info)) { printf("Error: Unable to use logfile. Exiting.\n"); exit(EXIT_FAILURE); } } /* lock / pid file */ pidfile = open(cfg.pidfile, O_RDWR|O_CREAT, 0644); if (pidfile<0) { perror("Error: pidfile"); snprintf(errorstring, 512, "opening pidfile \"%s\" failed (%s), exiting.", cfg.pidfile, strerror(errno)); printe(PT_Error); exit(EXIT_FAILURE); /* can't open */ } if (lockf(pidfile,F_TLOCK,0)<0) { perror("Error: pidfile lock"); snprintf(errorstring, 512, "pidfile \"%s\" lock failed (%s), exiting.", cfg.pidfile, strerror(errno)); printe(PT_Error); exit(EXIT_FAILURE); /* can't lock */ } /* close all descriptors except lock file */ for (i=getdtablesize();i>=0;--i) { if (i!=pidfile) { close(i); } } /* redirect standard i/o to null */ i=open("/dev/null",O_RDWR); /* stdin */ /* stdout */ if (dup(i) < 0) { perror("Error: dup(stdout)"); snprintf(errorstring, 512, "dup(stdout) failed, exiting."); printe(PT_Error); exit(EXIT_FAILURE); } /* stderr */ if (dup(i) < 0) { perror("Error: dup(stderr)"); snprintf(errorstring, 512, "dup(stderr) failed, exiting."); printe(PT_Error); exit(EXIT_FAILURE); } umask(027); /* set newly created file permissions */ /* change running directory */ if (chdir("/") < 0) { perror("Error: chdir(/)"); snprintf(errorstring, 512, "directory change to / failed, exiting."); printe(PT_Error); exit(EXIT_FAILURE); } /* first instance continues */ snprintf(str, 10, "%d\n", (int)getpid()); /* record pid to pidfile */ if (write(pidfile,str,strlen(str)) < 0) { perror("Error: write(pidfile)"); snprintf(errorstring, 512, "writing to pidfile %s failed, exiting.", cfg.pidfile); printe(PT_Error); exit(EXIT_FAILURE); } signal(SIGCHLD,SIG_IGN); /* ignore child */ signal(SIGTSTP,SIG_IGN); /* ignore tty signals */ signal(SIGTTOU,SIG_IGN); signal(SIGTTIN,SIG_IGN); if (cfg.uselogging==1) { snprintf(errorstring, 512, "Daemon running with pid %d.", (int)getpid()); printe(PT_Info); } }
void UserProc::execute() { ArgList new_args; char **argv; char **argp; char **envp; sigset_t sigmask; MyString a_out_name; MyString shortname; int user_syscall_fd = -1; const int READ_END = 0; const int WRITE_END = 1; int pipe_fds[2]; FILE *cmd_fp; char buf[128]; ReliSock *new_reli = NULL; pipe_fds[0] = -1; pipe_fds[1] = -1; shortname.formatstr( "condor_exec.%d.%d", cluster, proc ); a_out_name.formatstr( "%s/%s/%s", Execute, local_dir, shortname.Value() ); // Set up arg vector according to class of job switch( job_class ) { case CONDOR_UNIVERSE_STANDARD: if( pipe(pipe_fds) < 0 ) { EXCEPT( "pipe()" );} dprintf( D_ALWAYS, "Pipe built\n" ); // The user process should not try to read commands from // 0, 1, or 2 since we'll be using the commands to redirect // those. if( pipe_fds[READ_END] < 14 ) { dup2( pipe_fds[READ_END], 14 ); close( pipe_fds[READ_END] ); pipe_fds[READ_END] = 14; } dprintf( D_ALWAYS, "New pipe_fds[%d,%d]\n", pipe_fds[0], pipe_fds[1] ); sprintf( buf, "%d", pipe_fds[READ_END] ); dprintf( D_ALWAYS, "cmd_fd = %s\n", buf ); new_args.AppendArg(shortname); new_args.AppendArg("-_condor_cmd_fd"); new_args.AppendArg(buf); break; case CONDOR_UNIVERSE_PVM: #if 1 EXCEPT( "Don't know how to deal with PVM jobs" ); #else new_args.AppendArg(shortname); new_args.AppendArg("-1"); new_args.AppendArg(in); new_args.AppendArg(out); new_args.AppendArg(err); #endif break; case CONDOR_UNIVERSE_VANILLA: if (privsep_enabled()) { EXCEPT("Don't know how to deal with Vanilla jobs"); } new_args.AppendArg(shortname.Value()); break; } new_args.AppendArgsFromArgList(args); // take care of USER_JOB_WRAPPER support_job_wrapper(a_out_name,&new_args); MyString exec_name; exec_name = a_out_name; // If privsep is turned on, then we need to use the PrivSep // Switchboard to launch the job // FILE* switchboard_in_fp; FILE* switchboard_err_fp; int switchboard_child_in_fd; int switchboard_child_err_fd; if (privsep_enabled()) { // create the pipes that we'll use to communicate // if (!privsep_create_pipes(switchboard_in_fp, switchboard_child_in_fd, switchboard_err_fp, switchboard_child_err_fd)) { EXCEPT("can't launch job: privsep_create_pipes failure"); } } argv = new_args.GetStringArray(); // Set an environment variable that tells the job where it may put scratch data // even if it moves to a different directory. // get the environment vector envp = env_obj.getStringArray(); // We may run more than one of these, so each needs its own // remote system call connection to the shadow if( job_class == CONDOR_UNIVERSE_PVM ) { new_reli = NewConnection( v_pid ); user_syscall_fd = new_reli->get_file_desc(); } // print out arguments to execve dprintf( D_ALWAYS, "Calling execve( \"%s\"", exec_name.Value() ); for( argp = argv; *argp; argp++ ) { // argv dprintf( D_ALWAYS | D_NOHEADER, ", \"%s\"", *argp ); } dprintf( D_ALWAYS | D_NOHEADER, ", 0" ); for( argp = envp; *argp; argp++ ) { // envp dprintf( D_ALWAYS | D_NOHEADER, ", \"%s\"", *argp ); } dprintf( D_ALWAYS | D_NOHEADER, ", 0 )\n" ); if( (pid = fork()) < 0 ) { EXCEPT( "fork" ); } if( pid == 0 ) { // the child // Block only these 3 signals which have special meaning for // checkpoint/restart purposes. Leave other signals ublocked // so that if we get an exception during the restart process, // we will get a core file to debug. sigemptyset( &sigmask ); // for some reason if we block these, the user process is unable // to unblock some or all of them. #if 0 sigaddset( &sigmask, SIGUSR1 ); sigaddset( &sigmask, SIGUSR2 ); sigaddset( &sigmask, SIGTSTP ); #endif sigprocmask( SIG_SETMASK, &sigmask, 0 ); // renice renice_self( "JOB_RENICE_INCREMENT" ); // make certain the syscall sockets which are being passed // to the user job are setup to be blocking sockets. this // is done by calling timeout(0) CEDAR method. // we must do this because the syscall lib does _not_ // expect to see any failures due to errno EAGAIN... if ( SyscallStream ) { SyscallStream->timeout(0); } if ( new_reli ) { new_reli->timeout(0); } // If I'm using privledge separation, connect to the procd. // we need to register a family with the procd for the newly // created process, so that the ProcD will allow us to send // signals to it // if (privsep_enabled() == true) { MyString procd_address; bool response; bool ret; ProcFamilyClient pfc; procd_address = get_procd_address(); ret = pfc.initialize(procd_address.Value()); if (ret == false) { EXCEPT("Failure to initialize the ProcFamilyClient object"); } ret = pfc.register_subfamily(getpid(), getppid(), 60, response); if (ret == false) { EXCEPT("Could not communicate with procd. Aborting."); } if (response == false) { EXCEPT("Procd refused to register job subfamily. Aborting."); } } // If there is a requested coresize for this job, enforce it. // Do it before the set_priv_final to ensure root can alter // the coresize to the requested amount. Otherwise, just // use whatever the current default is. if (coredump_limit_exists == TRUE) { limit( RLIMIT_CORE, coredump_limit, CONDOR_HARD_LIMIT, "max core size" ); } // child process should have only it's submitting uid, and cannot // switch back to root or some other uid. // It'd be nice to check for errors here, but // unfortunately, we can't, since this only returns the // previous priv state, not whether it worked or not. // -Derek Wright 4/30/98 set_user_priv_final(); switch( job_class ) { case CONDOR_UNIVERSE_STANDARD: // if we're using PrivSep, the chdir here could fail. instead, // we pass the job's IWD to the switchboard via pipe // if (!privsep_enabled()) { if( chdir(local_dir) < 0 ) { EXCEPT( "chdir(%s)", local_dir ); } } close( pipe_fds[WRITE_END] ); break; case CONDOR_UNIVERSE_PVM: if( chdir(local_dir) < 0 ) { EXCEPT( "chdir(%s)", local_dir ); } close( pipe_fds[WRITE_END] ); dup2( user_syscall_fd, RSC_SOCK ); break; case CONDOR_UNIVERSE_VANILLA: set_iwd(); open_std_file( 0 ); open_std_file( 1 ); open_std_file( 2 ); (void)close( RSC_SOCK ); (void)close( CLIENT_LOG ); break; } // Make sure we're not root if( getuid() == 0 ) { // EXCEPT( "We're about to start as root, aborting." ); // You can't see this error message at all. So, just // exit(4), which is what EXCEPT normally gives. exit( 4 ); } #if defined( LINUX ) && (defined(I386) || defined(X86_64)) // adjust the execution domain of the child to be suitable for // checkpointing. patch_personality(); #endif // if we're using privsep, we'll exec the PrivSep Switchboard // first, which is setuid; it will then setuid to the user we // give it and exec the real job // if (privsep_enabled()) { close(fileno(switchboard_in_fp)); close(fileno(switchboard_err_fp)); privsep_get_switchboard_command("exec", switchboard_child_in_fd, switchboard_child_err_fd, exec_name, new_args); deleteStringArray(argv); argv = new_args.GetStringArray(); } // Everything's ready, start it up... errno = 0; execve( exec_name.Value(), argv, envp ); // A successful call to execve() never returns, so it is an // error if we get here. A number of errors are possible // but the most likely is that there is insufficient swap // space to start the new process. We don't try to log // anything, since we have the UID/GID of the job's owner // and cannot write into the log files... exit( JOB_EXEC_FAILED ); } // The parent // PrivSep - we have at this point only spawned the switchboard // with the "exec" command. we need to use our pipe to it in // order to tell it how to execute the user job, and then use // the error pipe to make sure everything worked // if (privsep_enabled()) { close(switchboard_child_in_fd); close(switchboard_child_err_fd); privsep_exec_set_uid(switchboard_in_fp, uid); privsep_exec_set_path(switchboard_in_fp, exec_name.Value()); privsep_exec_set_args(switchboard_in_fp, new_args); privsep_exec_set_env(switchboard_in_fp, env_obj); privsep_exec_set_iwd(switchboard_in_fp, local_dir); privsep_exec_set_inherit_fd(switchboard_in_fp, pipe_fds[0]); privsep_exec_set_inherit_fd(switchboard_in_fp, RSC_SOCK); privsep_exec_set_inherit_fd(switchboard_in_fp, CLIENT_LOG); privsep_exec_set_is_std_univ(switchboard_in_fp); fclose(switchboard_in_fp); if (!privsep_get_switchboard_response(switchboard_err_fp)) { EXCEPT("error starting job: " "privsep get_switchboard_response failure"); } } dprintf( D_ALWAYS, "Started user job - PID = %d\n", pid ); if( job_class != CONDOR_UNIVERSE_VANILLA ) { // Send the user process its startup environment conditions close( pipe_fds[READ_END] ); cmd_fp = fdopen( pipe_fds[WRITE_END], "w" ); dprintf( D_ALWAYS, "cmd_fp = %p\n", cmd_fp ); if( is_restart() ) { #if 1 fprintf( cmd_fp, "restart\n" ); dprintf( D_ALWAYS, "restart\n" ); #else fprintf( cmd_fp, "restart %s\n", target_ckpt ); dprintf( D_ALWAYS, "restart %s\n", target_ckpt ); #endif fprintf( cmd_fp, "end\n" ); dprintf( D_ALWAYS, "end\n" ); } else { fprintf( cmd_fp, "end\n" ); dprintf( D_ALWAYS, "end\n" ); } fclose( cmd_fp ); } deleteStringArray(argv); deleteStringArray(envp); state = EXECUTING; if( new_reli ) { delete new_reli; } // removed some vanilla-specific code here // ASSERT(job_class != CONDOR_UNIVERSE_VANILLA); }
void daemonize() { pid_t pid, sid, parent; char *lockfile; lockfile = "/var/lock/subsys/" DAEMON_NAME; openlog(DAEMON_NAME, LOG_PID, LOG_LOCAL5); /* already a daemon */ if ( getppid() == 1 ) return; /* Create the lock file as the current user */ /* if ( lockfile && lockfile[0] ) { lfp = open(lockfile,O_RDWR|O_CREAT,0660); if ( lfp < 0 ) { fprintf(stderr,"Unable to create lock file %s\n", lockfile); syslog( LOG_ERR, "unable to create lock file %s, code=%d (%s)", lockfile, errno, strerror(errno) ); exit(EXIT_FAILURE); } } */ /* Drop user if there is one, and we were run as root */ if ( getuid() == 0 || geteuid() == 0 ) { struct passwd *pw = getpwnam(RUN_AS_USER); if ( pw ) { syslog( LOG_NOTICE, "setting user to " RUN_AS_USER ); setuid( pw->pw_uid ); } } /* Trap signals that we expect to recieve */ signal(SIGCHLD,child_handler); signal(SIGUSR1,child_handler); signal(SIGALRM,child_handler); /* Fork off the parent process */ pid = fork(); if (pid < 0) { syslog( LOG_ERR, "unable to fork daemon, code=%d (%s)", errno, strerror(errno) ); exit(EXIT_FAILURE); } /* If we got a good PID, then we can exit the parent process. */ if (pid > 0) { /* Wait for confirmation from the child via SIGTERM or SIGCHLD, or for two seconds to elapse (SIGALRM). pause() should not return. */ alarm(2); pause(); exit(EXIT_FAILURE); } /* At this point we are executing as the child process */ parent = getppid(); syslog(LOG_INFO, "Starting daemon " DAEMON_NAME); /* Cancel certain signals */ signal(SIGCHLD,SIG_DFL); /* A child process dies */ signal(SIGTSTP,SIG_IGN); /* Various TTY signals */ signal(SIGTTOU,SIG_IGN); signal(SIGTTIN,SIG_IGN); signal(SIGHUP, SIG_IGN); /* Ignore hangup signal */ signal(SIGTERM,sigterm_handler); /* Die on SIGTERM */ /* Change the file mode mask */ umask(0); /* Create a new SID for the child process */ sid = setsid(); if (sid < 0) { syslog( LOG_ERR, "unable to create a new session, code %d (%s)", errno, strerror(errno) ); exit(EXIT_FAILURE); } /* Change the current working directory. This prevents the current directory from being locked; hence not being able to remove it. */ if ((chdir("/")) < 0) { syslog( LOG_ERR, "unable to change directory to %s, code %d (%s)", "/", errno, strerror(errno) ); exit(EXIT_FAILURE); } /* // write our pid to /var/run/DAEMON_NAME.pid pid_filename = "/var/run/" DAEMON_NAME ".pid"; pid_file = fopen(pid_filename, "w"); if (pid_file != NULL) { fprintf(pid_file, "%d\n", getpid()); } else { syslog (LOG_ERR, "Unable to create pid file %s %d %s", pid_filename, errno, strerror(errno)); } */ /* Redirect standard files to /dev/null */ freopen( "/dev/null", "r", stdin); freopen( "/dev/null", "w", stdout); freopen( "/var/tmp/" DAEMON_NAME, "w", stderr); chmod( "/var/tmp/" DAEMON_NAME, 0660); /* Tell the parent process that we are A-okay */ kill( parent, SIGUSR1 ); } // daemonize()
int main(int argc, char *argv[]) { fd_set rfds; /* the structure for the select call */ int code; /* return code from system calls */ char out_buff[MAXLINE]; /* from child and stdin */ int out_flag[MAXLINE] ; /* initialize the output flags */ char *program; /* a string to hold the child program invocation */ char **pargs = 0; /* holds parts of the command line */ int not_command = 1; /* a flag while parsing the command line */ /* try to get a pseudoterminal to play with */ if (ptyopen(&contNum, &serverNum, controllerPath, serverPath) == -1) { perror("ptyopen failed"); exit(-1); } /* call the routine that handles signals */ catch_signals(); /* parse the command line arguments - as with the aixterm the command argument -e should be last on the line. */ while(*++argv && not_command) { if(!strcmp(*argv, "-f")) load_wct_file(*++argv); else if(!strcmp(*argv, "-e")) { not_command = 0; pargs = ++argv; } else { fprintf(stderr, "usage: clef [-f fname] -e command\n"); exit(-1); } } skim_wct(); #ifdef log sprintf(logpath, "/tmp/cleflog%d", getpid()); logfd = open(logpath, O_CREAT | O_RDWR, 0666); #endif /* get the original termio settings, so the child has them */ if(tcgetattr(0,&childbuf) == -1) { perror("clef trying to get the initial terminal settings"); exit(-1); } /* start the child process */ child_pid = fork(); switch(child_pid) { case -1 : perror("clef can't create a new process"); exit(-1); case 0: /* CHILD */ /* Dissasociate form my parents group so all my child processes look at my terminal as the controlling terminal for the group */ setsid(); serverNum = open(serverPath,O_RDWR); if (serverNum == -1) perror("open serverPath failed"); /* since I am the child, I can close ptc, and dup pts for all it standard descriptors */ if (dup2(serverNum, 0) == -1) perror("dup2 0 failed"); if (dup2(serverNum, 1) == -1) perror("dup2 1 failed"); if (dup2(serverNum, 2) == -1) perror("dup2 2 failed"); if( (dup2(serverNum, 0) == -1) || (dup2(serverNum, 1) == -1) || (dup2(serverNum, 2) == -1) ) { perror("clef trying to dup2"); exit(-1); } /* since they have been duped, close them */ close(serverNum); close(contNum); /* To make sure everything is nice, set off enhedit */ /* childbuf.c_line = 0; */ /* reconfigure the child's terminal get echoing */ if(tcsetattr(0, TCSAFLUSH, &childbuf) == -1) { perror("clef child trying to set child's terminal"); exit(-1); } /* fire up the child's process */ if(pargs){ execvp( pargs[0], pargs); perror("clef trying to execvp its argument"); fprintf(stderr, "Process --> %s\n", pargs[0]); } else{ program = getenv("SHELL"); if (!program) program = strdup("/bin/sh"); else program = strdup (program); execlp( program,program, 0); perror("clef trying to execlp the default child"); fprintf(stderr, "Process --> %s\n", program); } exit(-1); break; /* end switch */ } /* PARENT */ /* Since I am the parent, I should start to initialize some stuff. I have to close the pts side for it to work properly */ close(serverNum); ppid = getppid(); /* Iinitialize some stuff for the reading and writing */ init_flag(out_flag, MAXLINE); define_function_keys(); init_reader(); PTY = 1; init_parent(); /* Here is the main loop, it simply starts reading characters from the std input, and from the child. */ while(1) { /* loop forever */ /* use select to see who has stuff waiting for me to handle */ /* set file descriptors for ptc and stdin */ FD_ZERO(&rfds); FD_SET(contNum,&rfds); FD_SET(0,&rfds); set_function_chars(); #ifdef log { char modepath[30]; sprintf(modepath, "\nMODE = %d\n", MODE); write(logfd, modepath, strlen(modepath)); } #endif #ifdef logterm { struct termio ptermio; char pbuff[1024]; tcgetattr(contNum, &ptermio); sprintf(pbuff, "child's settings: Lflag = %d, Oflag = %d, Iflag = %d\n", ptermio.c_lflag, ptermio.c_oflag, ptermio.c_iflag); write(logfd, pbuff, strlen(pbuff)); } #endif code = select(FD_SETSIZE,(void *) &rfds, NULL, NULL, NULL); for(; code < 0 ;) { if(errno == EINTR) { check_flip(); code = select(FD_SETSIZE,(void *) &rfds, NULL, NULL, NULL); } else { perror("clef select failure"); exit(-1); } } /* reading from the child **/ if( FD_ISSET(contNum,&rfds)) { if( (num_read = read(contNum, out_buff, MAXLINE)) == -1) { num_read = 0; } #ifdef log write(logfd, "OUT<<<<<", strlen("OUT<<<<<")); write(logfd, out_buff, num_read); #endif if(num_read > 0) { /* now do the printing to the screen */ if(MODE!= CLEFRAW) { back_up(buff_pntr); write(1,out_buff, num_read); print_whole_buff(); /* reprint the input buffer */ } else write(1,out_buff, num_read); } } /* done the child stuff */ /* I should read from std input */ else { if(FD_ISSET(0,&rfds)) { num_read = read(0, in_buff, MAXLINE); #ifdef log write(logfd, "IN<<<<<", strlen("IN<<<<<")); write(logfd, in_buff, num_read); #endif check_flip(); if(MODE == CLEFRAW ) write(contNum, in_buff, num_read); else do_reading(); } } } }
int main (int argc, char **argv) { char *user_line = NULL, *qp_reply = NULL; size_t qp_reply_len = 0, user_len = 0; int ret = 0; /* reading to the from Quickplot */ FILE *file_from = NULL; char path_to[FIFO_PATH_LEN], path_from[FIFO_PATH_LEN]; *path_to = '\0'; *path_from = '\0'; if(argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))) usage(); if(argc == 2 && argv[1][0] > '0' && argv[1][0] < '9') { char *end; pid = strtoul(argv[1], &end, 10); if(*end != '\0') { printf("Cannot parse PID from \"%s\"\n\n", argv[1]); usage(); } } if(pid == -1) { char *qp_path; size_t len; len = strlen(argv[0]); /* remove the _shell part of stuff/path_to/quickplot_shell */ if(len >= 15) { qp_path = qp_strdup(argv[0]); qp_path[len-6] = '\0'; } else qp_path = qp_strdup("quickplot"); signal(SIGUSR1, usr1_catcher); errno = 0; pid = fork(); if(pid == -1) { QP_EERROR("failed to fork()\n"); return 1; } if(pid != 0) { // parent runs quickplot char **e_argv; int i; char last_arg[64]; e_argv = qp_malloc((argc+2)*sizeof(*e_argv)); e_argv[0] = qp_strdup("quickplot"); for(i=1;i<argc;++i) e_argv[i] = argv[i]; snprintf(last_arg, 64, "--signal=%d", pid); e_argv[i++] = last_arg; e_argv[i] = NULL; execv(qp_path, e_argv); QP_EERROR("failed to execute %s\n", qp_path); // we failed, kill my child. kill(pid, SIGINT); return 1; // failed } else { pid = getppid(); /* wait for sig SIGCONT */ DEBUG("pid=%d waiting for signal\n", getpid()); while(!got_usr1) usleep(100000); DEBUG("pid=%d got signal\n", getpid()); } } errno = 0; if(kill(pid, SIGCONT)) { QP_EERROR("Failed to signal pid %d\n", pid); return 1; } errno = 0; if(mkfifo(set_to_qp_fifo_path(path_to, pid, getpid()), S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP)) { QP_EERROR("Failed to create fifo %s\n", path_to); *path_to = '\0'; ret = 1; goto cleanup; } errno = 0; if(mkfifo(set_from_qp_fifo_path(path_from, pid, getpid()), S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP)) { QP_EERROR("Failed to create fifo %s\n", path_from); *path_from = '\0'; ret = 1; goto cleanup; } /* Since the FIFO block on fopen(,"r") we will signal * before we call fopen(,"r"). * * Looks like fopen(,"w") blocks too. */ errno = 0; if(kill(pid, SIGUSR1)) { QP_EERROR("Failed to signal pid %d\n", pid); return 1; } errno = 0; if(!(file_to = fopen(path_to, "w"))) { QP_EERROR("fopen(\"%s\",\"a\") failed\n", path_to); ret = 1; goto cleanup_with_signal; } errno = 0; if(!(file_from = fopen(path_from, "r"))) { QP_EERROR("fopen(\"%s\",\"r\") failed\n", path_from); ret = 1; goto cleanup_with_signal; } setlinebuf(file_from); prompt = allocate_prompt(); #ifdef QP_DEBUG signal(SIGSEGV, debug_sighandler); signal(SIGABRT, debug_sighandler); #endif signal(SIGTERM, term_sighandler); signal(SIGQUIT, term_sighandler); signal(SIGINT, term_sighandler); stdin_isatty = isatty(fileno(stdin)); qp_shell_initialize(1); #ifdef HAVE_LIBREADLINE if(stdin_isatty) { use_readline = 1; printf("Using readline version: %d.%d\n", RL_VERSION_MAJOR, RL_VERSION_MINOR); } else { #else printf("Using getline()\n"); #endif #ifdef HAVE_LIBREADLINE } #endif /* Exercise the pipe so it does not block the Quickplot * service on fopen(,"r"). */ fprintf(file_to, "start\n"); fflush(file_to); if(read_and_spew_until_end(&qp_reply, &qp_reply_len, file_from, pid)) goto cleanup_with_signal; /* We can hide the FIFO files now that both parties are connected. * The OS will keep the FIFO files in existence so long as one of * the two processes have them open. */ unlink(path_to); *path_to = '\0'; unlink(path_from); *path_from = '\0'; while((Getline(&user_line, &user_len))) { char **argv; int argc; size_t len; char *history_mem = NULL; len = strlen(user_line) + 1; argv = get_args(user_line, &argc); if(argc > 0) { if(!strcmp("exit", *argv)) // exit break; if(!strcmp("quit", *argv)) // quit { fprintf(file_to, "quit\n"); fflush(file_to); break; } if(process_client_side_commands(&argc, &argv, stdin, stdout, len, &history_mem #ifdef HAVE_LIBREADLINE , 0, &use_readline #endif )) { if(!strcmp("input", *argv) && argc > 1) { stdin_isatty = isatty(fileno(stdin)); } } else // command to server { int i; #ifdef QP_DEBUG if(SPEW_LEVEL() <= 1) { printf("Read user line: \"%s\"", argv[0]); for(i=1; i<argc; ++i) printf(" %s", argv[i]); printf("\n"); } #endif fprintf(file_to, "%s", argv[0]); for(i=1; i<argc; ++i) fprintf(file_to, " %s", argv[i]); fprintf(file_to,"\n"); fflush(file_to); // read and print reply if(read_and_spew_until_end(&qp_reply, &qp_reply_len, file_from, pid)) goto cleanup_with_signal; } } if(history_mem) free(history_mem); free(argv); } #ifdef HAVE_READLINE_HISTORY Save_history(); #endif cleanup_with_signal: signal_exit(); cleanup: if(*path_to) unlink(path_to); if(*path_from) unlink(path_from); printf("exiting\n"); return ret; }
void exo_I_b(int* i){ if(*i<N_FILS){ pid_t pid; pid=fork(); *i = *i + 1; switch(pid){ case -1: fprintf(stderr,"Erreur lors de la création du fils"); exit(EXIT_FAILURE); case 0: printf("Je suis un processus fils, mon pid est le %d, mon père est %d \n",getpid(),getppid()); exit(0); default: exo_I_b(i); } } exit(EXIT_SUCCESS); }
void ngx_signal_handler(int signo) { char *action; ngx_int_t ignore; ngx_err_t err; ngx_signal_t *sig; ignore = 0; err = ngx_errno; for (sig = signals; sig->signo != 0; sig++) { if (sig->signo == signo) { break; } } ngx_time_sigsafe_update(); action = ""; switch (ngx_process) { case NGX_PROCESS_MASTER: case NGX_PROCESS_SINGLE: switch (signo) { case ngx_signal_value(NGX_SHUTDOWN_SIGNAL): ngx_quit = 1; action = ", shutting down"; break; case ngx_signal_value(NGX_TERMINATE_SIGNAL): case SIGINT: ngx_terminate = 1; action = ", exiting"; break; case ngx_signal_value(NGX_NOACCEPT_SIGNAL): ngx_noaccept = 1; action = ", stop accepting connections"; break; case ngx_signal_value(NGX_RECONFIGURE_SIGNAL): ngx_reconfigure = 1; action = ", reconfiguring"; break; case ngx_signal_value(NGX_REOPEN_SIGNAL): ngx_reopen = 1; action = ", reopening logs"; break; case ngx_signal_value(NGX_CHANGEBIN_SIGNAL): if (getppid() > 1 || ngx_new_binary > 0) { /* * Ignore the signal in the new binary if its parent is * not the init process, i.e. the old binary's process * is still running. Or ignore the signal in the old binary's * process if the new binary's process is already running. */ action = ", ignoring"; ignore = 1; break; } ngx_change_binary = 1; action = ", changing binary"; break; case SIGALRM: ngx_sigalrm = 1; break; case SIGIO: ngx_sigio = 1; break; case SIGCHLD: ngx_reap = 1; break; } break; case NGX_PROCESS_WORKER: case NGX_PROCESS_HELPER: switch (signo) { case ngx_signal_value(NGX_NOACCEPT_SIGNAL): ngx_debug_quit = 1; case ngx_signal_value(NGX_SHUTDOWN_SIGNAL): ngx_quit = 1; action = ", shutting down"; break; case ngx_signal_value(NGX_TERMINATE_SIGNAL): case SIGINT: ngx_terminate = 1; action = ", exiting"; break; case ngx_signal_value(NGX_REOPEN_SIGNAL): ngx_reopen = 1; action = ", reopening logs"; break; case ngx_signal_value(NGX_RECONFIGURE_SIGNAL): case ngx_signal_value(NGX_CHANGEBIN_SIGNAL): case SIGIO: action = ", ignoring"; break; } break; } ngx_log_error(NGX_LOG_NOTICE, ngx_cycle->log, 0, "signal %d (%s) received%s", signo, sig->signame, action); if (ignore) { ngx_log_error(NGX_LOG_CRIT, ngx_cycle->log, 0, "the changing binary signal is ignored: " "you should shutdown or terminate " "before either old or new binary's process"); } if (signo == SIGCHLD) { ngx_process_get_status(); } ngx_set_errno(err); }
// Attendre tous les fils, void exo_II_2(){ int i; pid_t pid; for(i=0;i<N_FILS;i++){ pid=fork(); switch(pid){ case -1: fprintf(stderr,"Erreur lors de l'appel à fork"); exit(EXIT_FAILURE); case 0: printf("Je suis un processus fils, mon pid est le %d, mon père est %d \n",getpid(),getppid()); exit(EXIT_SUCCESS); default: wait(NULL); } } exit(EXIT_SUCCESS); }
int main() { printf("pid=%d\n",getpid()); printf("ppid=%d\n",getppid()); return EXIT_SUCCESS; }
int main(int argc, char **argv) { KAboutData about("kstcmd", I18N_NOOP("Kst Command Line"), "1.0", I18N_NOOP("Kst Command Line"), KAboutData::License_GPL, I18N_NOOP("(c) 2005-2006 The University of Toronto"), 0, "http://kst.kde.org/"); about.addAuthor("Staikos Computing Services Inc.", I18N_NOOP("Developed for the University of Toronto"), "*****@*****.**"); KCmdLineArgs::init(argc, argv, &about); KCmdLineArgs::addCmdLineOptions(options); KApplication a(false, false); QCString session; KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); if (args->count() > 0) { session = args->arg(0); } setvbuf(stdout, 0, _IONBF, 0); if (session.isEmpty()) { DCOPClient *client = KApplication::dcopClient(); QCStringList apps = client->registeredApplications(); QCStringList ksts; for (QCStringList::ConstIterator i = apps.begin(); i != apps.end(); ++i) { if ((*i).left(4) == "kst-") { ksts += *i; } } if (ksts.isEmpty()) { char *l = readline(_T("Kst does not appear to be running. Start a new session? ")); if (!l) { return ERR_NONE; } QString lstr = l; free(l); l = 0L; if (lstr.stripWhiteSpace().lower()[0] != 'y') { return ERR_NONE; } int pid = 0; QString err; int rc = KApplication::startServiceByDesktopName("kst", QString::null, &err, &session, &pid); if (rc != 0) { printf(_T("Error starting session: %s\n"), err.latin1()); return ERR_STARTING_SESSION; } if (session.isEmpty()) { session = QString("kst-%1").arg(pid).latin1(); } time_t startTime = time(NULL); printf("%s", _T("Waiting for Kst to start.")); while (!client->isApplicationRegistered(session)) { if (time(NULL) - startTime > 30) { printf("%s", _T("\nTimeout waiting for Kst to start\n")); return ERR_STARTING_SESSION; } printf("."); sleep(1); } printf("\n"); } else if (ksts.count() > 1) { QCString parentKst = QCString("kst-") + QString::number(getppid()).latin1(); if (ksts.contains(parentKst)) { session = parentKst; } else { printf("%s", _T("Please choose a session number to attach to:\n")); int j = 0; for (QCStringList::ConstIterator i = ksts.begin(); i != ksts.end(); ++i) { printf(_T("%2d: %s\n"), ++j, (*i).data()); } printf("> "); char choice[10]; QString l = fgets(choice, 4, stdin); l = l.stripWhiteSpace(); if (l.isEmpty()) { printf("%s", _T("No session found.\n")); return ERR_NO_SESSION; } bool ok = false; int nchoice = l.toInt(&ok); if (ok && nchoice > 0 && nchoice <= j) { session = ksts[nchoice - 1]; } else { printf("%s", _T("No session found.\n")); return ERR_NO_SESSION; } } } else { session = ksts[0]; } } DCOPRef ref(session.data(), "KstScript"); if (ref.isNull() || !KApplication::dcopClient()->registeredApplications().contains(ref.app())) { printf(_T("Error attaching to session %s\n"), session.data()); return ERR_ATTACHING; } printf(_T("Attached to Kst session %s\n"), session.data()); return run(ref); }
int main(int argc, char **argv) { if (getppid() != 1) { fprintf(stderr, "Parent process must be init.\n"); return EXIT_FAILURE; } time_t start = time(NULL); // If these fail, there's not really anywhere to complain... freopen(TEMPORARY_LOG_FILE, "a", stdout); setbuf(stdout, NULL); freopen(TEMPORARY_LOG_FILE, "a", stderr); setbuf(stderr, NULL); fprintf(stderr, "Starting Open Recovery on %s", ctime(&start)); //menu title //lite - just the base //full - look for mod #if OPEN_RCVR_VERSION_LITE MENU_TITLE = BASE_MENU_TITLE; #else //keep'em malloced even if empty :p char* mod_author = malloc(81); char* mod_version = malloc(81); char mod_author_prop[81]; char mod_version_prop[81]; property_get(MOD_AUTHOR_PROP, mod_author_prop, ""); property_get(MOD_VERSION_PROP, mod_version_prop, ""); //assume there are some mod properties, leave NULL if there ain't MENU_TITLE = malloc((sizeof(BASE_MENU_TITLE) + 3) * sizeof(char*)); memset(MENU_TITLE, 0, (sizeof(BASE_MENU_TITLE) + 3) * sizeof(char*)); char** b = BASE_MENU_TITLE; char** m = MENU_TITLE; while (*b) { *m = *b; m++; b++; } //append "" if one of the props exist int append_empty = 0; if (mod_author_prop[0] != '\0') { //mod version only if mod author if (mod_version_prop[0] != '\0') { snprintf(mod_version, 80, MOD_VERSION_BASE, mod_version_prop); *m = mod_version; m++; } snprintf(mod_author, 80, MOD_AUTHOR_BASE, mod_author_prop); *m = mod_author; m++; append_empty = 1; } if (append_empty) { *m = malloc(1); (*m)[0] = '\0'; m++; } #endif ui_init(); //react on the command //full version only checks for it's own command file //the rest is done by lite version #if OPEN_RCVR_VERSION_LITE get_args(&argc, &argv); #else argc = 1; get_cmd_file_args(&argc, &argv); #endif int previous_runs = 0; const char *send_intent = NULL; const char *update_package = NULL; int wipe_data = 0, wipe_cache = 0; int arg; while ((arg = getopt_long(argc, argv, "", OPTIONS, NULL)) != -1) { switch (arg) { case 'p': previous_runs = atoi(optarg); break; case 's': send_intent = optarg; break; case 'u': update_package = optarg; break; case 'w': wipe_data = wipe_cache = 1; break; case 'c': wipe_cache = 1; break; case '?': LOGE("Invalid command argument\n"); continue; } } device_recovery_start(); fprintf(stderr, "Command:"); for (arg = 0; arg < argc; arg++) fprintf(stderr, " \"%s\"", argv[arg]); fprintf(stderr, "\n\n"); property_list(print_property, NULL); fprintf(stderr, "\n"); int status = INSTALL_SUCCESS; if (update_package != NULL) { status = install_package(update_package); if (status != INSTALL_SUCCESS) ui_print("Installation aborted.\n"); char package_path[PATH_MAX] = ""; if (!ensure_root_path_mounted(update_package) && translate_root_path(update_package, package_path, sizeof(package_path))) unlink(package_path); } else if (wipe_data) { if (device_wipe_data()) status = INSTALL_ERROR; if (erase_root("DATA:")) status = INSTALL_ERROR; if (wipe_cache && erase_root("CACHE:")) status = INSTALL_ERROR; if (status != INSTALL_SUCCESS) ui_print("Data wipe failed.\n"); } else if (wipe_cache) { if (wipe_cache && erase_root("CACHE:")) status = INSTALL_ERROR; if (status != INSTALL_SUCCESS) ui_print("Cache wipe failed.\n"); } else status = INSTALL_ERROR; // No command specified #if OPEN_RCVR_VERSION_LITE int or_up_sts = install_package(FULL_PACKAGE_FILE); if (or_up_sts != INSTALL_SUCCESS) { ui_print("Failed to switch into the full version.\n"); ui_print("Running Lite version only.\n"); } #endif //lite OR doesn't have text visible by default //but full OR does #if OPEN_RCVR_VERSION_LITE if (status != INSTALL_SUCCESS) ui_set_background(BACKGROUND_ICON_ERROR); if (status != INSTALL_SUCCESS || ui_text_visible()) prompt_and_wait(); #else if (status != INSTALL_SUCCESS) { ui_set_background(BACKGROUND_ICON_ERROR); prompt_and_wait(); } #endif // If there is a radio image pending, reboot now to install it. maybe_install_firmware_update(send_intent); // Otherwise, get ready to boot the main system... finish_recovery(send_intent); ui_print("Rebooting...\n"); sync(); ensure_common_roots_unmounted(); reboot(RB_AUTOBOOT); return EXIT_SUCCESS; }
/******************************************************************************* * This function is executed in the main thread after its run loop gets * kicked from within kextd_kernel_request_loop(). *******************************************************************************/ void kextd_handle_kernel_request(void * info) { PTLockTakeLock(gKernelRequestQueueLock); while (!queue_empty(&g_request_queue)) { request_t * load_request = NULL; // must free request_t * this_load_request = NULL; // free if duplicate unsigned int type; char * kmod_name = NULL; // must release load_request = (request_t *)queue_first(&g_request_queue); queue_remove(&g_request_queue, load_request, request_t *, link); /***** * Scan the request queue for duplicates of the first one and * pull them out. */ this_load_request = (request_t *)queue_first(&g_request_queue); while (!queue_end((request_t *)&g_request_queue, this_load_request)) { request_t * next_load_request = NULL; // don't free next_load_request = (request_t *) queue_next(&this_load_request->link); if (load_request_equal(load_request, this_load_request)) { queue_remove(&g_request_queue, this_load_request, request_t *, link); free(this_load_request->kmodname); free(this_load_request); } this_load_request = next_load_request; } PTLockUnlock(gKernelRequestQueueLock); type = load_request->type; kmod_name = load_request->kmodname; free(load_request); if (kmod_name) { KXKextManagerError load_result; static boolean_t have_signalled_load = FALSE; kextd_load_kext(kmod_name, &load_result); free(kmod_name); if ((load_result == kKXKextManagerErrorNone || load_result == kKXKextManagerErrorAlreadyLoaded) && !have_signalled_load && (getppid() > 1)) { // ppid == 1 => parent is no longer waiting have_signalled_load = TRUE; int ret; if (g_verbose_level >= 1) { kextd_log("running kextcache"); } ret = system(KEXTCACHE_COMMAND); if (ret != 0) { kextd_error_log("kextcache exec(%d)", ret); } } } PTLockTakeLock(gKernelRequestQueueLock); } PTLockUnlock(gKernelRequestQueueLock); return; }
int forkinet(int port) { FILE *fp; char logbuf[256]; int status; int sock; int pipeid[2]; pid_t cpid; /* process id of the child */ /* create the pipe */ if (pipe(pipeid) <0) return -1; /* make the pipe unblocking * * as we are dealing with a pipe a message is * either sent or discarded. So there is no possibility * that the task will hang - however if the inet processing * fork does not empty the pipe quickly enough, it is possible * for a record to be lost. */ if ((status=fcntl(pipeid[1],F_GETFL))==-1) return -1; status|=O_NONBLOCK; if ((status=fcntl(pipeid[1],F_SETFL,status))==-1) return -1; if ((cpid=fork()) !=0) { close(pipeid[0]); return pipeid[1]; } close(pipeid[1]); loginfo(logfname,"Child Server Process Starting"); sock=createsocket(&port); if (sock !=-1) { pid_t pid; fp=fopen(pname,"w"); fprintf(fp,"%d\n",port); fclose(fp); sprintf(logbuf,"Listening on port %d.",port); loginfo(logfname,logbuf); sprintf(logbuf,"Port number recorded in file %s.",pname); loginfo(logfname,logbuf); sprintf(logbuf,"Time of last packet recorded in file %s.",timefname); loginfo(logfname,logbuf); fp=fopen(pidname,"w"); pid=getppid(); sprintf(logbuf,"Process ID recorded in file %s.",pidname); loginfo(logfname,logbuf); sprintf(logbuf,"Parent PID %d.",(int) pid); loginfo(logfname,logbuf); fprintf(fp,"%d\n",(int) pid); pid=getpid(); sprintf(logbuf,"Child PID %d.",(int) pid); loginfo(logfname,logbuf); fprintf(fp,"%d\n",(int) pid); fclose(fp); } else loginfo(logfname,"Failed to create socket"); if (sock !=-1) processsocket(sock,pipeid[0]); close(sock); close(pipeid[0]); loginfo(logfname,"Child Server Process Terminating"); exit(0); return -1; }
int main(int argc, char *argv[]){ unsigned char stop, temp; unsigned char cmd; unsigned char arg1, arg2; char arg1buf[4], arg2buf[4]; packet recievepkt; packet sendpkt; int fd_joy; // File Descriptor for joystick int temp1; struct js_event e; temp1 = 0; // Set first time stamp to zero fd_joy = open_joystick(); // /Initalize the joystick // printf("fd_joy: %d\n", fd_joy); strncpy(device, argv[1], DEVICE_MAX_SIZE); //set up serial port if((fd = configDevice()) < 2){ perror("Error opening/configuring device\n"); return -1; } menu(); //set handler for close command signal(SIGUSR2, catchClose); signal(SIGTERM, catchClose); //create timer for ping pid = fork(); if (pid < 0) printf("Error creating ping timer process\n"); else if(pid == 0){ //die if parent dies prctl(PR_SET_PDEATHSIG, SIGHUP); //set alarm for ping timeout signal(SIGALRM, sendPing); //prime Timeout reset handler signal(SIGUSR1, catchTimeoutReset); alarm(PING_INTERVAL); for(timeouts = 0; timeouts < PING_RETRIES;){ //spin wheels. exit if ping timeout occurs } //kill parent process if ping timeout printf("Ping timeout. %d unanswered pings\n", timeouts); //tell parent to exit kill(getppid(), SIGKILL); return 1; } int readcount; char zeroflag; //main control loop for(stop = 0; stop <= 0;){ //cmd = 'V'; //arg1 = 0; //arg2 = 0; /*scanf("%c %s %s%c", &cmd, arg1buf, arg2buf, NULL); //get command //strcpy(arg1buf, "Z"); arg1 = (unsigned char)atoi(arg1buf); arg2 = (unsigned char)atoi(arg2buf); if(arg1 == 0){ arg1 = 1; } if(arg2 == 0){ arg2 = 1; }*/ readcount = read (fd_joy, &e, sizeof(e)); //printf("servo: %d\r", e.time); //printf("bytes read from joystick: %d\n", readcount); //if(e.time > temp1) { //printf("Bryan\n"); if(e.type == 1 && e.value == 1){ if(e.time > temp1){ button_press(e.number); temp1 = e.time; } } if(e.type == 2 /*&& e.value != 0*/){ if(!zeroflag){ axis_press(e.number, e.value); } //set zeroflag if event input zero //necessary to not keep resending packages //when in the zero (stopped) position zeroflag = (e.value == 0) ? 1 : 0; //printf("zeroflag %c\n", zeroflag); } } //while((temp = getchar()) != '\n' && temp != EOF); //clear buffer //printf("CMD: %c ARG1: %c ARG2: %c\n", cmd, arg1, arg2); //stop = parseCommand(cmd, arg1, arg2); } close(fd); //tell child to exit kill(pid, SIGUSR2); t1.join(); scanf("", NULL); return 0; }
int main( int argc, char** argv ) { int err = 0; std::string argOutputDir; std::string symbolFile; std::string configFile; std::string password; bool printDebug; bool isLogging; int zero = 0; (void) signal(SIGINT, sighandler); (void) signal(SIGTERM, sighandler); (void) signal(SIGHUP, sighandler); g_zmq_context = zmq_init(1); assert(g_zmq_context); pub_socket = zmq_socket(g_zmq_context, ZMQ_PUB); zmq_setsockopt(pub_socket, ZMQ_LINGER, &zero, sizeof(zero)); assert(pub_socket); GOOGLE_PROTOBUF_VERIFY_VERSION; try { po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("c", po::value<std::string>(), "<config file>") ("s", po::value<std::string>(), "<symbol file>") ("o", po::value<std::string>(), "<output path>") ("nolog", po::value<int>()->implicit_value(0), "disable logging (FIX and tick)") ("d", "debug info") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("nolog")) { std::cout << "Logging disabled" << std::endl; //isLogging = (vm["nolog"].as<int>() == 1 ? false : true); isLogging = false; } else { std::cout << "Logging enabled" << std::endl; isLogging = true; } if (vm.count("help")) { std::cout << desc << "\n"; return 1; } if (vm.count("o")) { std::cout << "Output path: " << vm["o"].as<std::string>() << "\n"; argOutputDir = vm["o"].as<std::string>(); } else { // set default std::cout << "Output path file was not set \n"; } if (vm.count("s")) { std::cout << "Symbol file: " << vm["s"].as<std::string>() << "\n"; symbolFile = vm["s"].as<std::string>(); } else { // use default name for symbols file name symbolFile = "symbols.cfg"; std::cout << "Using default symbols file: symbols.cfg\n"; } if (vm.count("c")) { std::cout << "Config file: " << vm["c"].as<std::string>() << ".\n"; configFile = vm["c"].as<std::string>(); } else { std::cout << "Config file was not set.\n"; err++; } printDebug = vm.count("d") > 0; /* moved passwords to cfg files if (vm.count("p")) { std::cout << "Pass: "******"p"].as<std::string>() << ".\n"; password = vm["p"].as<std::string>(); } else { std::cout << "Password was not set.\n"; err++; } */ } catch(std::exception& e) { std::cerr << "EXCEPTION:" << e.what(); return 1; } if (err > 0) { std::cout << "Aborting due to missing parameters.\n"; return 1; } /* * @see http://www.boost.org/doc/libs/1_41_0/doc/html/program_options.html */ std::vector<std::string> symbols = readSymbols(symbolFile); try { FIX::SessionSettings settings(configFile); std::set<FIX::SessionID> sessions = settings.getSessions (); assert(sessions.size() == 1); FIX::SessionID sessionId = *(sessions.begin()); const FIX::Dictionary& dict = settings.get(sessionId); ApplicationConfig config; // MIC code for adding to output filename config.mic_string = dict.has("MIC") ? dict.getString("MIC") : ""; std::cout << "My MIC is: " << config.mic_string << std::endl; capk::get_config_params(g_zmq_context, "tcp://127.0.0.1:11111", &all_venue_config); capkproto::venue_configuration my_config = capk::get_venue_config(&all_venue_config, config.mic_string.c_str()); std::cout << "Received config:\n" << my_config.DebugString() << std::endl; // venue id as for protobuf usage to identify venue if (my_config.venue_id() == "") { std::cerr << "venue_id not set!" << std::endl; exit(-1); } else { // boost version of atoi if (qi::parse(my_config.venue_id().begin(), my_config.venue_id().end(), qi::int_, config.venue_id) == false) { std::cout << "Can't parse venue_id" << std::endl; exit(-1); } if (config.venue_id == 0) { std::cerr << "venue_id can not be 0" << std::endl; exit(-1); } std::cout << "Set venue_id to: " << config.venue_id << std::endl; } // Username and password settings config.username = dict.has("Username") ? dict.getString("Username") : ""; config.password = dict.has("Password") ? dict.getString("Password") : ""; config.sendPasswordInRawDataField = dict.has("SendPasswordInRawData") && dict.getBool("SendPasswordInRawData"); // Should use aggregated book? config.aggregatedBook = dict.has("AggregatedBook") && dict.getBool("AggregatedBook"); std::cout << "Aggregated book: " << config.aggregatedBook << std::endl; // Should we reset sequence numbers? bool bReset = dict.has("ResetSeqNo") && dict.getBool("ResetSeqNo"); std::cout << "Resetting sequence numbers: " << bReset << std::endl; // How to send market data requests - bulk or multiple messages config.sendIndividualMarketDataRequests = dict.has("SendIndividualMarketDataRequests") && dict.getBool("SendIndividualMarketDataRequests"); std::cout << "Send individual market data requests: " << config.sendIndividualMarketDataRequests << std::endl; // Fix Version string config.version = dict.has("FIXVersion") ? (FIXVersion)atoi(dict.getString("FIXVersion").c_str()) : FIX_42; std::cout << "Using FIX version: " << config.version << std::endl; // Market depth std::string depth = dict.has("MarketDepth") ? dict.getString("MarketDepth") : ""; config.marketDepth = atoi(depth.c_str()); std::cout << "Setting market depth: " << config.marketDepth << std::endl; // Update Type long updateType = dict.has("MDUpdateType") ? dict.getLong("MDUpdateType") : -1; std::cout << "Setting update type: " << updateType << std::endl; // Debug settings config.printDebug = printDebug; Application application(bReset, config); papplication = &application; application.addSymbols(symbols); // if user specified an output dir, then put files into date-sorted // subdirectories, otherwise put into the default dirs specified in // config file std::string orderBooksOutputDir = "."; std::string logOutputDir = dict.has("FileLogPath") ? dict.getString("FileLogPath") : "."; std::string storeOutputDir = dict.has("FileStorePath") ? dict.getString("FileStorePath") : "."; if (argOutputDir.length() > 0) { orderBooksOutputDir = argOutputDir; fs::path argPath = fs::path(argOutputDir); if (!fs::exists(argPath)) { fs::create_directories(argPath); } /* put both order books and message logs in subdirs, but put the store at the root dir */ fs::path logOutputPath = argPath / fs::path("log"); if (!fs::exists(logOutputPath)) { fs::create_directory(logOutputPath); } logOutputDir = logOutputPath.string(); fs::path storeOutputPath = argPath / fs::path("store"); if (!fs::exists(storeOutputPath)) { fs::create_directory(storeOutputPath); } storeOutputDir = storeOutputPath.string(); } pid_t pid = getpid(); pid_t ppid = getppid(); printf("pid: %d, ppid: %d\n", pid, ppid); std::string pidFileName = std::string(argv[0]) + "." + config.mic_string + std::string(".pid"); std::ofstream pidFile(pidFileName); if (pidFile.is_open()) { pidFile << pid; pidFile.flush(); } else { std::cerr << "Can't write pid file - exiting"; exit(-1); } // Get the bind address for zmq sockets bool isPublishing = dict.has("should_publish_prices") && dict.getBool("should_publish_prices"); if (isPublishing) { std::cout << "Collector is publishing prices to: " << my_config.market_data_broadcast_addr() << std::endl; } else { std::cout << "Collector is NOT publishing prices" << std::endl; } // ZMQ initialization if (isPublishing) { zmq_bind(pub_socket, my_config.market_data_broadcast_addr().c_str()); application.setZMQContext(g_zmq_context); application.setZMQSocket(pub_socket); } application.setPublishing(isPublishing); application.setLogging(isLogging); // Set MDUpdateType application.setUpdateType(updateType); // orderbook output setup application.setDataPath(orderBooksOutputDir); // fix logging params if (isLogging) { std::cout << "Logging with FileStoreFactory" << std::endl; FIX::FileStoreFactory fileStoreFactory(storeOutputDir); FIX::FileLogFactory logFactory(logOutputDir); pinitiator = new FIX::SocketInitiator(application, fileStoreFactory, settings, logFactory); } else { std::cout << "Logging with NullStoreFactory" << std::endl; FIX::NullStoreFactory nullStoreFactory; pinitiator = new FIX::SocketInitiator(application, nullStoreFactory, settings); } //pinitiator = &initiator; std::cout << "Starting initiator" << std::endl; pinitiator->start(); char x; while(std::cin >> x) { if (x == 'q') { break; } } std::cout << "Stopping initiator..." << std::endl; pinitiator->stop(); return 0; } catch ( FIX::Exception & e ) { std::cout << e.what(); return 1; } }
/** * make this program run detached from the current console */ static int daemonize(void) { pid_t pid; pid_t sid; int pfd[2]; int res; // already a daemon if (getppid() == 1) return 0; if((res = pipe(pfd)) < 0) { usbmuxd_log(LL_FATAL, "pipe() failed."); return res; } pid = fork(); if (pid < 0) { usbmuxd_log(LL_FATAL, "fork() failed."); return pid; } if (pid > 0) { // exit parent process int status; close(pfd[1]); if((res = read(pfd[0],&status,sizeof(int))) != sizeof(int)) { fprintf(stderr, "usbmuxd: ERROR: Failed to get init status from child, check syslog for messages.\n"); exit(1); } if(status != 0) fprintf(stderr, "usbmuxd: ERROR: Child process exited with error %d, check syslog for messages.\n", status); exit(status); } // At this point we are executing as the child process // but we need to do one more fork daemon_pipe = pfd[1]; close(pfd[0]); report_to_parent = 1; // Create a new SID for the child process sid = setsid(); if (sid < 0) { usbmuxd_log(LL_FATAL, "setsid() failed."); return -1; } pid = fork(); if (pid < 0) { usbmuxd_log(LL_FATAL, "fork() failed (second)."); return pid; } if (pid > 0) { // exit parent process close(daemon_pipe); exit(0); } // Change the current working directory. if ((chdir("/")) < 0) { usbmuxd_log(LL_FATAL, "chdir() failed"); return -2; } // Redirect standard files to /dev/null if (!freopen("/dev/null", "r", stdin)) { usbmuxd_log(LL_FATAL, "Redirection of stdin failed."); return -3; } if (!freopen("/dev/null", "w", stdout)) { usbmuxd_log(LL_FATAL, "Redirection of stdout failed."); return -3; } return 0; }
PreProcessFilter::PreProcessFilter(const string& filterCommand) : m_toFilter(NULL), m_fromFilter(NULL) { // Child error signal install // sigaction is the replacement for the traditional signal() method #if (!defined(WIN32) && !defined(WIN64)) struct sigaction action; action.sa_handler = exec_failed; sigemptyset(&action.sa_mask); action.sa_flags = 0; if (sigaction(SIGUSR1, &action, NULL) < 0) { perror("SIGUSR1 install error"); exit(EXIT_FAILURE); } int pipe_status; int pipefds_input[2]; int pipefds_output[2]; // int pipefds_error[2]; // Create the pipes // We do this before the fork so both processes will know about // the same pipe and they can communicate. #ifdef _MSC_VER pipe_status = _pipe(pipefds_input); #else pipe_status = pipe(pipefds_input); #endif if (pipe_status == -1) { perror("Error creating the pipe"); exit(EXIT_FAILURE); } pipe_status = pipe(pipefds_output); if (pipe_status == -1) { perror("Error creating the pipe"); exit(EXIT_FAILURE); } /* pipe_status = pipe(pipefds_error); if (pipe_status == -1) { perror("Error creating the pipe"); exit(EXIT_FAILURE); } */ pid_t pid; // Create child process; both processes continue from here pid = fork(); if (pid == pid_t(0)) { // Child process // When the child process finishes sends a SIGCHLD signal // to the parent // Tie the standard input, output and error streams to the // appropiate pipe ends // The file descriptor 0 is the standard input // We tie it to the read end of the pipe as we will use // this end of the pipe to read from it dup2 (CHILD_STDIN_READ,0); dup2 (CHILD_STDOUT_WRITE,1); // dup2 (CHILD_STDERR_WRITE,2); // Close in the child the unused ends of the pipes close(CHILD_STDIN_WRITE); close(CHILD_STDOUT_READ); //close(CHILD_STDERR_READ); // Execute the program execl("/bin/bash", "bash", "-c", filterCommand.c_str() , (char*)NULL); // We should never reach this point // Tell the parent the exec failed kill(getppid(), SIGUSR1); exit(EXIT_FAILURE); } else if (pid > pid_t(0)) { // Parent // Close in the parent the unused ends of the pipes close(CHILD_STDIN_READ); close(CHILD_STDOUT_WRITE); // close(CHILD_STDERR_WRITE); m_toFilter = new ofdstream(CHILD_STDIN_WRITE); m_fromFilter = new ifdstream(CHILD_STDOUT_READ); } else { perror("Error: fork failed"); exit(EXIT_FAILURE); } #else std::cerr << "Unsupported on Windows platform (PreProcessFilter)" << std::endl; #endif }
/* Functions */ void sqlite3_plugin(int pipe_fd, struct configuration *cfgptr, void *ptr) { struct pkt_data *data; struct ports_table pt; struct pollfd pfd; struct insert_data idata; time_t refresh_deadline; int timeout, refresh_timeout, amqp_timeout; int ret, num; struct ring *rg = &((struct channels_list_entry *)ptr)->rg; struct ch_status *status = ((struct channels_list_entry *)ptr)->status; struct plugins_list_entry *plugin_data = ((struct channels_list_entry *)ptr)->plugin; int datasize = ((struct channels_list_entry *)ptr)->datasize; u_int32_t bufsz = ((struct channels_list_entry *)ptr)->bufsize; pid_t core_pid = ((struct channels_list_entry *)ptr)->core_pid; struct networks_file_data nfd; char *dataptr; unsigned char *rgptr; int pollagain = TRUE; u_int32_t seq = 1, rg_err_count = 0; struct extra_primitives extras; struct primitives_ptrs prim_ptrs; #ifdef WITH_RABBITMQ struct p_amqp_host *amqp_host = &((struct channels_list_entry *)ptr)->amqp_host; #endif memcpy(&config, cfgptr, sizeof(struct configuration)); memcpy(&extras, &((struct channels_list_entry *)ptr)->extras, sizeof(struct extra_primitives)); recollect_pipe_memory(ptr); pm_setproctitle("%s [%s]", "SQLite3 Plugin", config.name); memset(&idata, 0, sizeof(idata)); if (config.pidfile) write_pid_file_plugin(config.pidfile, config.type, config.name); if (config.logfile) { fclose(config.logfile_fd); config.logfile_fd = open_output_file(config.logfile, "a", FALSE); } sql_set_signals(); sql_init_default_values(&extras); SQLI_init_default_values(&idata); SQLI_set_callbacks(&sqlfunc_cbr); sql_set_insert_func(); /* some LOCAL initialization AFTER setting some default values */ reload_map = FALSE; idata.now = time(NULL); refresh_deadline = idata.now; idata.cfg = &config; sql_init_maps(&extras, &prim_ptrs, &nt, &nc, &pt); sql_init_global_buffers(); sql_init_historical_acct(idata.now, &idata); sql_init_triggers(idata.now, &idata); sql_init_refresh_deadline(&refresh_deadline); if (config.pipe_amqp) { plugin_pipe_amqp_compile_check(); #ifdef WITH_RABBITMQ pipe_fd = plugin_pipe_amqp_connect_to_consume(amqp_host, plugin_data); amqp_timeout = plugin_pipe_set_retry_timeout(&amqp_host->btimers, pipe_fd); #endif } else setnonblocking(pipe_fd); /* setting number of entries in _protocols structure */ while (_protocols[protocols_number].number != -1) protocols_number++; /* building up static SQL clauses */ idata.num_primitives = SQLI_compose_static_queries(); glob_num_primitives = idata.num_primitives; /* setting up environment variables */ SQL_SetENV(); sql_link_backend_descriptors(&bed, &p, &b); /* plugin main loop */ for(;;) { poll_again: status->wakeup = TRUE; calc_refresh_timeout(refresh_deadline, idata.now, &refresh_timeout); pfd.fd = pipe_fd; pfd.events = POLLIN; timeout = MIN(refresh_timeout, (amqp_timeout ? amqp_timeout : INT_MAX)); ret = poll(&pfd, (pfd.fd == ERR ? 0 : 1), timeout); if (ret <= 0) { if (getppid() == 1) { Log(LOG_ERR, "ERROR ( %s/%s ): Core process *seems* gone. Exiting.\n", config.name, config.type); exit_plugin(1); } if (ret < 0) goto poll_again; } idata.now = time(NULL); if (config.sql_history) { while (idata.now > (idata.basetime + idata.timeslot)) { time_t saved_basetime = idata.basetime; idata.basetime += idata.timeslot; if (config.sql_history == COUNT_MONTHLY) idata.timeslot = calc_monthly_timeslot(idata.basetime, config.sql_history_howmany, ADD); glob_basetime = idata.basetime; idata.new_basetime = saved_basetime; glob_new_basetime = saved_basetime; } } #ifdef WITH_RABBITMQ if (config.pipe_amqp && pipe_fd == ERR) { if (timeout == amqp_timeout) { pipe_fd = plugin_pipe_amqp_connect_to_consume(amqp_host, plugin_data); amqp_timeout = plugin_pipe_set_retry_timeout(&amqp_host->btimers, pipe_fd); } else amqp_timeout = plugin_pipe_calc_retry_timeout_diff(&amqp_host->btimers, idata.now); } #endif switch (ret) { case 0: /* timeout */ if (qq_ptr) sql_cache_flush(queries_queue, qq_ptr, &idata, FALSE); sql_cache_handle_flush_event(&idata, &refresh_deadline, &pt); break; default: /* we received data */ read_data: if (!config.pipe_amqp) { if (!pollagain) { seq++; seq %= MAX_SEQNUM; if (seq == 0) rg_err_count = FALSE; idata.now = time(NULL); } else { if ((ret = read(pipe_fd, &rgptr, sizeof(rgptr))) == 0) exit_plugin(1); /* we exit silently; something happened at the write end */ } if ((rg->ptr + bufsz) > rg->end) rg->ptr = rg->base; if (((struct ch_buf_hdr *)rg->ptr)->seq != seq) { if (!pollagain) { pollagain = TRUE; goto poll_again; } else { rg_err_count++; if (config.debug || (rg_err_count > MAX_RG_COUNT_ERR)) { Log(LOG_WARNING, "WARN ( %s/%s ): Missing data detected (plugin_buffer_size=%llu plugin_pipe_size=%llu).\n", config.name, config.type, config.buffer_size, config.pipe_size); Log(LOG_WARNING, "WARN ( %s/%s ): Increase values or look for plugin_buffer_size, plugin_pipe_size in CONFIG-KEYS document.\n\n", config.name, config.type); } seq = ((struct ch_buf_hdr *)rg->ptr)->seq; } } pollagain = FALSE; memcpy(pipebuf, rg->ptr, bufsz); rg->ptr += bufsz; } #ifdef WITH_RABBITMQ else { ret = p_amqp_consume_binary(amqp_host, pipebuf, config.buffer_size); if (ret) pipe_fd = ERR; seq = ((struct ch_buf_hdr *)pipebuf)->seq; amqp_timeout = plugin_pipe_set_retry_timeout(&amqp_host->btimers, pipe_fd); } #endif /* lazy sql refresh handling */ if (idata.now > refresh_deadline) { if (qq_ptr) sql_cache_flush(queries_queue, qq_ptr, &idata, FALSE); sql_cache_handle_flush_event(&idata, &refresh_deadline, &pt); } else { if (config.sql_trigger_exec) { while (idata.now > idata.triggertime && idata.t_timeslot > 0) { sql_trigger_exec(config.sql_trigger_exec); idata.triggertime += idata.t_timeslot; if (config.sql_trigger_time == COUNT_MONTHLY) idata.t_timeslot = calc_monthly_timeslot(idata.triggertime, config.sql_trigger_time_howmany, ADD); } } } data = (struct pkt_data *) (pipebuf+sizeof(struct ch_buf_hdr)); if (config.debug_internal_msg) Log(LOG_DEBUG, "DEBUG ( %s/%s ): buffer received cpid=%u seq=%u num_entries=%u\n", config.name, config.type, core_pid, seq, ((struct ch_buf_hdr *)pipebuf)->num); if (!config.pipe_check_core_pid || ((struct ch_buf_hdr *)pipebuf)->core_pid == core_pid) { while (((struct ch_buf_hdr *)pipebuf)->num > 0) { for (num = 0; primptrs_funcs[num]; num++) (*primptrs_funcs[num])((u_char *)data, &extras, &prim_ptrs); for (num = 0; net_funcs[num]; num++) (*net_funcs[num])(&nt, &nc, &data->primitives, prim_ptrs.pbgp, &nfd); if (config.ports_file) { if (!pt.table[data->primitives.src_port]) data->primitives.src_port = 0; if (!pt.table[data->primitives.dst_port]) data->primitives.dst_port = 0; } if (config.pkt_len_distrib_bins_str && config.what_to_count_2 & COUNT_PKT_LEN_DISTRIB) evaluate_pkt_len_distrib(data); prim_ptrs.data = data; (*insert_func)(&prim_ptrs, &idata); ((struct ch_buf_hdr *)pipebuf)->num--; if (((struct ch_buf_hdr *)pipebuf)->num) { dataptr = (unsigned char *) data; if (!prim_ptrs.vlen_next_off) dataptr += datasize; else dataptr += prim_ptrs.vlen_next_off; data = (struct pkt_data *) dataptr; } } } if (!config.pipe_amqp) goto read_data; } } }