static int doit(int s, const char *host, const char *user, const char *outfilename, const char *header_str, int leavep, int verbose, int forkp) { int ret; char out_buf[PUSH_BUFSIZ]; int out_len = 0; char *in_buf; size_t in_buf_size; size_t in_len = 0; char *in_ptr; pop_state state = INIT; unsigned count = 0, bytes; unsigned asked_for = 0, retrieved = 0, asked_deleted = 0, deleted = 0; unsigned sent_xdele = 0; int out_fd; char from_line[128]; size_t from_line_length; time_t now; struct write_state write_state; unsigned int numheaders = 1; char **headers = NULL; int i; char *tmp = NULL; in_buf = emalloc(PUSH_BUFSIZ + 1); in_ptr = in_buf; in_buf_size = PUSH_BUFSIZ; if (do_from) { char *tmp2; tmp2 = tmp = estrdup(header_str); out_fd = -1; if (verbose) fprintf (stderr, "%s@%s\n", user, host); while (*tmp != '\0') { tmp = strchr(tmp, ','); if (tmp == NULL) break; tmp++; numheaders++; } headers = emalloc(sizeof(char *) * (numheaders + 1)); for (i = 0; i < numheaders; i++) { headers[i] = strtok_r(tmp2, ",", &tmp2); } headers[numheaders] = NULL; } else { out_fd = open(outfilename, O_WRONLY | O_APPEND | O_CREAT, 0666); if (out_fd < 0) err (1, "open %s", outfilename); if (verbose) fprintf (stderr, "%s@%s -> %s\n", user, host, outfilename); } now = time(NULL); from_line_length = snprintf (from_line, sizeof(from_line), "From %s %s", "push", ctime(&now)); if (from_line_length < 0 || from_line_length > sizeof(from_line)) errx (1, "snprintf failed"); out_len = snprintf (out_buf, sizeof(out_buf), "USER %s\r\nPASS hej\r\nSTAT\r\n", user); if (out_len < 0 || out_len > sizeof(out_buf)) errx (1, "snprintf failed"); if (net_write (s, out_buf, out_len) != out_len) err (1, "write"); if (verbose > 1) fprintf (stderr, "%s", out_buf); if (!do_from) write_state_init (&write_state, out_fd); while(state != QUIT) { fd_set readset, writeset; FD_ZERO(&readset); FD_ZERO(&writeset); if (s >= FD_SETSIZE) errx (1, "fd too large"); FD_SET(s,&readset); if (verbose > 1) fprintf (stderr, "state: %s count: %d asked_for: %d " "retrieved: %d asked_deleted: %d\n", pop_state_string[state], count, asked_for, retrieved, asked_deleted); if (((state == STAT || state == RETR || state == TOP) && asked_for < count) || (state == XDELE && !sent_xdele) || (state == DELE && asked_deleted < count)) FD_SET(s,&writeset); ret = select (s + 1, &readset, &writeset, NULL, NULL); if (ret < 0) { if (errno == EAGAIN) continue; else err (1, "select"); } if (FD_ISSET(s, &readset)) { char *beg, *p; size_t rem; int blank_line = 0; if(in_len >= in_buf_size) { char *tmp = erealloc(in_buf, in_buf_size + PUSH_BUFSIZ + 1); in_ptr = tmp + (in_ptr - in_buf); in_buf = tmp; in_buf_size += PUSH_BUFSIZ; } ret = read (s, in_ptr, in_buf_size - in_len); if (ret < 0) err (1, "read"); else if (ret == 0) errx (1, "EOF during read"); in_len += ret; in_ptr += ret; *in_ptr = '\0'; beg = in_buf; rem = in_len; while(rem > 1 && (p = strstr(beg, "\r\n")) != NULL) { if (state == TOP) { char *copy = beg; for (i = 0; i < numheaders; i++) { size_t len; len = min(p - copy + 1, strlen(headers[i])); if (strncasecmp(copy, headers[i], len) == 0) { fprintf (stdout, "%.*s\n", (int)(p - copy), copy); } } if (beg[0] == '.' && beg[1] == '\r' && beg[2] == '\n') { if (numheaders > 1) fprintf (stdout, "\n"); state = STAT; if (++retrieved == count) { state = QUIT; net_write (s, "QUIT\r\n", 6); if (verbose > 1) fprintf (stderr, "QUIT\r\n"); } } rem -= p - beg + 2; beg = p + 2; } else if (state == RETR) { char *copy = beg; if (beg[0] == '.') { if (beg[1] == '\r' && beg[2] == '\n') { if(!blank_line) write_state_add(&write_state, "\n", 1); state = STAT; rem -= p - beg + 2; beg = p + 2; if (++retrieved == count) { write_state_flush (&write_state); if (fsync (out_fd) < 0) err (1, "fsync"); close(out_fd); if (leavep) { state = QUIT; net_write (s, "QUIT\r\n", 6); if (verbose > 1) fprintf (stderr, "QUIT\r\n"); } else { if (forkp) { pid_t pid; pid = fork(); if (pid < 0) warn ("fork"); else if(pid != 0) { if(verbose) fprintf (stderr, "(exiting)"); return 0; } } state = XDELE; if (verbose) fprintf (stderr, "deleting... "); } } continue; } else ++copy; } *p = '\n'; if(blank_line && strncmp(copy, "From ", min(p - copy + 1, 5)) == 0) write_state_add(&write_state, ">", 1); write_state_add(&write_state, copy, p - copy + 1); blank_line = (*copy == '\n'); rem -= p - beg + 2; beg = p + 2; } else if (rem >= 3 && strncmp (beg, "+OK", 3) == 0) { if (state == STAT) { if (!do_from) write_state_add(&write_state, from_line, from_line_length); blank_line = 0; if (do_from) state = TOP; else state = RETR; } else if (state == XDELE) { state = QUIT; net_write (s, "QUIT\r\n", 6); if (verbose > 1) fprintf (stderr, "QUIT\r\n"); break; } else if (state == DELE) { if (++deleted == count) { state = QUIT; net_write (s, "QUIT\r\n", 6); if (verbose > 1) fprintf (stderr, "QUIT\r\n"); break; } } else if (++state == STAT) { if(sscanf (beg + 4, "%u %u", &count, &bytes) != 2) errx(1, "Bad STAT-line: %.*s", (int)(p - beg), beg); if (verbose) { fprintf (stderr, "%u message(s) (%u bytes). " "fetching... ", count, bytes); if (do_from) fprintf (stderr, "\n"); } else if (do_count) { fprintf (stderr, "%u message(s) (%u bytes).\n", count, bytes); } if (count == 0) { state = QUIT; net_write (s, "QUIT\r\n", 6); if (verbose > 1) fprintf (stderr, "QUIT\r\n"); break; } } rem -= p - beg + 2; beg = p + 2; } else { if(state == XDELE) { state = DELE; rem -= p - beg + 2; beg = p + 2; } else errx (1, "Bad response: %.*s", (int)(p - beg), beg); } } if (!do_from) write_state_flush (&write_state); memmove (in_buf, beg, rem); in_len = rem; in_ptr = in_buf + rem; } if (FD_ISSET(s, &writeset)) { if ((state == STAT && !do_from) || state == RETR) out_len = snprintf (out_buf, sizeof(out_buf), "RETR %u\r\n", ++asked_for); else if ((state == STAT && do_from) || state == TOP) out_len = snprintf (out_buf, sizeof(out_buf), "TOP %u 0\r\n", ++asked_for); else if(state == XDELE) { out_len = snprintf(out_buf, sizeof(out_buf), "XDELE %u %u\r\n", 1, count); sent_xdele++; } else if(state == DELE) out_len = snprintf (out_buf, sizeof(out_buf), "DELE %u\r\n", ++asked_deleted); if (out_len < 0 || out_len > sizeof(out_buf)) errx (1, "snprintf failed"); if (net_write (s, out_buf, out_len) != out_len) err (1, "write"); if (verbose > 1) fprintf (stderr, "%s", out_buf); } } if (verbose) fprintf (stderr, "Done\n"); if (do_from) { free (tmp); free (headers); } else { write_state_destroy (&write_state); } return 0; }
/** * Does the chdir, fork, setsid, etc. to become a daemon process. * * @param pidfile #NULL, or pidfile to create * @param print_pid_pipe pipe to print daemon's pid to, or -1 for none * @param error return location for errors * @param keep_umask #TRUE to keep the original umask * @returns #FALSE on failure */ dbus_bool_t _dbus_become_daemon (const DBusString *pidfile, DBusPipe *print_pid_pipe, DBusError *error, dbus_bool_t keep_umask) { const char *s; pid_t child_pid; int dev_null_fd; _dbus_verbose ("Becoming a daemon...\n"); _dbus_verbose ("chdir to /\n"); if (chdir ("/") < 0) { dbus_set_error (error, DBUS_ERROR_FAILED, "Could not chdir() to root directory"); return FALSE; } _dbus_verbose ("forking...\n"); switch ((child_pid = fork ())) { case -1: _dbus_verbose ("fork failed\n"); dbus_set_error (error, _dbus_error_from_errno (errno), "Failed to fork daemon: %s", _dbus_strerror (errno)); return FALSE; break; case 0: _dbus_verbose ("in child, closing std file descriptors\n"); /* silently ignore failures here, if someone * doesn't have /dev/null we may as well try * to continue anyhow */ dev_null_fd = open ("/dev/null", O_RDWR); if (dev_null_fd >= 0) { dup2 (dev_null_fd, 0); dup2 (dev_null_fd, 1); s = _dbus_getenv ("DBUS_DEBUG_OUTPUT"); if (s == NULL || *s == '\0') dup2 (dev_null_fd, 2); else _dbus_verbose ("keeping stderr open due to DBUS_DEBUG_OUTPUT\n"); } if (!keep_umask) { /* Get a predictable umask */ _dbus_verbose ("setting umask\n"); umask (022); } _dbus_verbose ("calling setsid()\n"); if (setsid () == -1) _dbus_assert_not_reached ("setsid() failed"); break; default: if (!_dbus_write_pid_to_file_and_pipe (pidfile, print_pid_pipe, child_pid, error)) { _dbus_verbose ("pid file or pipe write failed: %s\n", error->message); kill (child_pid, SIGTERM); return FALSE; } _dbus_verbose ("parent exiting\n"); _exit (0); break; } return TRUE; }
List* execString(cmdLog* cLog, List* env, char* incoming) { cmdLine* line; cmdLine* firstLine; cmdLine* currLine; int pipeCounter = 0; int * pid; int pid2; int i; int j; int **pipefd; line = parseCmdLines(incoming); currLine = line; firstLine = line; if (line==NULL || !strcmp(line->arguments[0], "quit")) { freeList(env); freeCmdLines(line); return (List*)-1; } line= cmdEnvReplace(env, line); if (!strcmp(line->arguments[0], "assign")) { env= cmdAssign(env, line); } else if (!strcmp(line->arguments[0], "unassign")) { env= cmdUnassign(env, line); } else if (!strcmp(line->arguments[0], "cd")) { cmdCD(cLog, line, incoming); } else if (line->arguments[0][0]=='!') { env= cmdReadLog(cLog, env, line); } else { j = 0; pushArray(cLog, incoming); if(line->next) { while(currLine != NULL) { currLine = currLine->next; pipeCounter++; } pipefd= createPipes(pipeCounter-1); pid = (int *)malloc(pipeCounter * sizeof(int)); if (!(pid[j] =fork())) { /* first son*/ close(STDOUT_FILENO); /* Close unused write end */ dup(rightPipe(pipefd, line)[1]); close(rightPipe(pipefd, line)[1]); coreExec(cLog, env, line); } close(rightPipe(pipefd, line)[1]); j++; line = line->next; for (i=0; i<pipeCounter-2; i++) { if (!(pid[j] =fork())) { /* first son*/ close(STDOUT_FILENO); /* Close unused write end */ dup(rightPipe(pipefd, line)[1]); close(rightPipe(pipefd, line)[1]); close(STDIN_FILENO); dup(leftPipe(pipefd, line)[0]); close(leftPipe(pipefd, line)[0]); coreExec(cLog, env, line); } close(leftPipe(pipefd, line)[0]); close(rightPipe(pipefd, line)[1]); j++; line = line->next; } if (!(pid[j] =fork())) { /* first son*/ close(STDIN_FILENO); /* Close unused write end */ dup(leftPipe(pipefd, line)[0]); close(leftPipe(pipefd, line)[0]); coreExec(cLog, env, line); } close(leftPipe(pipefd, line)[0]); for(i=0; i<=j; i++) { if(line->blocking!=0) { waitpid(pid[i],0,0); } } releasePipes(pipefd, pipeCounter-1); } else { if (!(pid2=fork())) { coreExec(cLog, env, line); } } if(line->blocking!=0) { waitpid(pid2,0,0); } } freeCmdLines(firstLine); free(pid); return env; }
//create worker child proccess static int swFactoryProcess_manager_start(swFactory *factory) { swFactoryProcess *object = factory->object; int i, pid, ret; int reactor_pti; swServer *serv = factory->ptr; if (serv->ipc_mode == SW_IPC_MSGQUEUE) { //读数据队列 if (swQueueMsg_create(&serv->read_queue, 1, serv->message_queue_key, 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(&serv->write_queue, 1, serv->message_queue_key + 1, 1) < 0) { swError("[Master] swPipeMsg_create[out] fail. Error: %s [%d]", strerror(errno), errno); return SW_ERR; } } } else { object->pipes = sw_calloc(serv->worker_num, sizeof(swPipe)); if (object->pipes == NULL) { swError("malloc[worker_pipes] failed. Error: %s [%d]", strerror(errno), errno); return SW_ERR; } //worker进程的pipes for (i = 0; i < serv->worker_num; i++) { if (swPipeUnsock_create(&object->pipes[i], 1, SOCK_DGRAM) < 0) { return SW_ERR; } serv->workers[i].pipe_master = object->pipes[i].getFd(&object->pipes[i], 1); serv->workers[i].pipe_worker = object->pipes[i].getFd(&object->pipes[i], 0); } } if (SwooleG.task_worker_num > 0) { key_t msgqueue_key = 0; if (SwooleG.task_ipc_mode == SW_IPC_MSGQUEUE) { msgqueue_key = serv->message_queue_key + 2; } if (swProcessPool_create(&SwooleG.task_workers, SwooleG.task_worker_num, serv->task_max_request, msgqueue_key) < 0) { swWarn("[Master] create task_workers failed."); return SW_ERR; } swTaskWorker_init(&SwooleG.task_workers); swWorker *worker; for(i = 0; i < SwooleG.task_worker_num; i++) { worker = swServer_get_worker(serv, serv->worker_num + i); if (swWorker_create(worker) < 0) { return SW_ERR; } } } pid = fork(); switch (pid) { //创建manager进程 case 0: //wait master process SW_START_SLEEP; if (SwooleGS->start == 0) { return SW_OK; } /** * create worker process */ for (i = 0; i < serv->worker_num; i++) { //close(worker_pipes[i].pipes[0]); reactor_pti = (i % serv->writer_num); serv->workers[i].reactor_id = reactor_pti; pid = swFactoryProcess_worker_spawn(factory, i); if (pid < 0) { swError("fork() failed."); return SW_ERR; } else { serv->workers[i].pid = pid; } } /** * create task worker process */ if (SwooleG.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; break; case -1: swError("fork() failed."); return SW_ERR; } return SW_OK; }
int main( int argc, char *argv[] ) { int five; int myint = 1; struct sockaddr_in server,client; sigemptyset((sigset_t *)&five); int init_fd = socket(AF_INET, SOCK_STREAM, 0); if (init_fd == -1) { perror("socket"); exit(-1); } bzero((char *) &server, sizeof(server)); if(setsockopt(init_fd,SOL_SOCKET,SO_REUSEADDR,&myint,sizeof(myint)) == -1){ perror("setsocket"); exit(-1); } server.sin_family = AF_INET; server.sin_addr.s_addr = htonl(INADDR_ANY); server.sin_port = htons(atoi(argv[1])); if (bind(init_fd, (struct sockaddr *) &server, sizeof(server)) == -1) { perror("bind"); exit(-1); } if((listen(init_fd,20)) == -1){ perror("listen"); exit(-1); } int addr_len = sizeof(client); while (1) { int fd = accept(init_fd,(struct sockaddr *)&client,(socklen_t*)&addr_len); if (fd < 0) { perror("accept"); exit(1); } pid_t pid = fork(); if (pid == -1) { perror("fork"); close(fd); } if (pid == 0){ alarm(15); close(init_fd); int user_priv = priv("tutorial"); if(!user_priv){ menu(fd); close(fd); exit(0); } }else{ close(fd); } } close(init_fd); }
int copy(char str[64],char name[32],int sym) { char *wdest=(char *)malloc(sizeof(char)*64);//"/tmp/"; strcpy(wdest,"/myfolder/"); char qqdest[24]="/myfolder/"; char wtype[8]=".sqlite"; char *qtype="."; //printf("~~~~~000%s\n", wdest); strcat(wdest,name); //printf("~~~~~111%s\n", wdest); strcat(qqdest,name); strcat(wdest,wtype); //printf("~~~~~222%s\n", wdest); //strcat(qqdest,qtype); int pid; if ((pid = fork()) < 0) { printf("fork ifuse error\n"); return 0; } else if (pid == 0) { if(sym==0) //qq { execl("/bin/cp","cp", "-r",str,qqdest, (char *)0 ); //-r delete } else if(sym==1) //weixin { //printf("%s\n", name); //printf("%s\n", wdest); execl("/bin/cp","cp", str,wdest, (char *)0 ); } else { execl("/bin/cp","cp","-r", str,"/myfolder/", (char *)0 ); } } free(wdest); int status; pid_t ret; ret=wait(&status); if(ret <0){ perror("wait error"); return 0; } if (WIFEXITED(status)) { printf("copy normal exit status=%d\n", WEXITSTATUS(status)); if(WEXITSTATUS(status)==1) { return 0; } else { return 1; } } else { printf("thread encounter error\n"); return 0; } }
////////////////////////////////////////////////////////////////////////////// // // Start // bool AppInit(int argc, char* argv[]) { boost::thread_group threadGroup; boost::thread* detectShutdownThread = NULL; bool fRet = false; try { // // Parameters // // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main() ParseParameters(argc, argv); if (!boost::filesystem::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str()); return false; } try { ReadConfigFile(mapArgs, mapMultiArgs); } catch(std::exception &e) { fprintf(stderr,"Error reading configuration file: %s\n", e.what()); return false; } // Check for -testnet or -regtest parameter (TestNet() calls are only valid after this clause) if (!SelectParamsFromCommandLine()) { fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n"); return false; } if (mapArgs.count("-?") || mapArgs.count("--help")) { // First part of help message is specific to bitcoind / RPC client std::string strUsage = _("Reddcoin Core Daemon") + " " + _("version") + " " + FormatFullVersion() + "\n\n" + _("Usage:") + "\n" + " reddcoind [options] " + _("Start Reddcoin Core Daemon") + "\n" + _("Usage (deprecated, use reddcoin-cli):") + "\n" + " reddcoind [options] <command> [params] " + _("Send command to Reddcoin Core") + "\n" + " reddcoind [options] help " + _("List commands") + "\n" + " reddcoind [options] help <command> " + _("Get help for a command") + "\n"; strUsage += "\n" + HelpMessage(HMM_BITCOIND); strUsage += "\n" + HelpMessageCli(false); fprintf(stdout, "%s", strUsage.c_str()); return false; } // Command-line RPC bool fCommandLine = false; for (int i = 1; i < argc; i++) if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "bitcoin:")) fCommandLine = true; if (fCommandLine) { int ret = CommandLineRPC(argc, argv); exit(ret); } #ifndef WIN32 fDaemon = GetBoolArg("-daemon", false); if (fDaemon) { fprintf(stdout, "Bitcoin server starting\n"); // Daemonize pid_t pid = fork(); if (pid < 0) { fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno); return false; } if (pid > 0) // Parent process, pid is child process id { CreatePidFile(GetPidFile(), pid); return true; } // Child process falls through to rest of initialization pid_t sid = setsid(); if (sid < 0) fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno); } #endif SoftSetBoolArg("-server", true); detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup)); fRet = AppInit2(threadGroup); } catch (std::exception& e) { PrintExceptionContinue(&e, "AppInit()"); } catch (...) { PrintExceptionContinue(NULL, "AppInit()"); } if (!fRet) { if (detectShutdownThread) detectShutdownThread->interrupt(); threadGroup.interrupt_all(); // threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of // the startup-failure cases to make sure they don't result in a hang due to some // thread-blocking-waiting-for-another-thread-during-startup case } if (detectShutdownThread) { detectShutdownThread->join(); delete detectShutdownThread; detectShutdownThread = NULL; } Shutdown(); return fRet; }
int main(int argc, char** argv){ struct addrinfo hints; struct addrinfo *res; int info, sd; int nread; char buf[BUF_SIZE]; char host[NI_MAXHOST]; char serv[NI_MAXSERV]; hints.ai_family = AF_UNSPEC; /*ipv4 o ipv6*/ hints.ai_socktype = SOCK_DGRAM; /*udp*/ hints.ai_flags = AI_PASSIVE; hints.ai_protocol = 0; if(argc < 1) perror("Error de argumentos.\n"); info = getaddrinfo("::", argv[1], &hints, &res); if(info != 0) perror("Error getaddrinfo.\n"); sd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); bind(sd, res->ai_addr, res->ai_addrlen); int i; for(i = 0; i < 2; i++){ pid_t pid = fork(); if(pid == -1) perror("Error de pid.\n"); else if(pid == 0) { while(1){ struct sockaddr_storage sock; socklen_t sock_len = sizeof(sock); nread = recvfrom(sd, buf, BUF_SIZE, 0, (struct sockaddr *) &sock, &sock_len); buf[nread] = '\0'; getnameinfo((struct sockaddr *) &sock, sock_len, host, NI_MAXHOST, serv, NI_MAXSERV, NI_NUMERICHOST | NI_NUMERICSERV); if(strcmp(buf, "a") == 0 || strcmp(buf, "a\n") == 0){ sendto(sd, host, strlen(host), 0, (struct sockaddr *) &sock, sock_len); } else if(strcmp(buf, "p") == 0 || strcmp(buf, "p\n") == 0) { sendto(sd, serv, strlen(serv), 0, (struct sockaddr *) &sock, sock_len); } else if(strcmp(buf, "q") == 0 || strcmp(buf, "q\n") == 0) { sendto(sd, "ADIÓS\n", 6, 0, (struct sockaddr *) &sock, sock_len); freeaddrinfo(res); close(sd); return 0; } printf("[H: %d,%d] Host: %s Puerto: %s\n", getpid(), i+1, host, serv); } } } i = 0; while(i<2){ int status; wait(&status); i++; } freeaddrinfo(res); close(sd); return 0; }
int main(int argc, char **argv) { int pi[2], pid,primero,termina,no_mas; long n; char *p, *fin, *ps, s2[BUFSIZ],s[BUFSIZ],nombre[250],st[250],text[70000],tit[1500],tit2[1500],tit0[1500], arg_nombre[250]; char resp_trabajo[100],nom_a_buscar[100] ,trabajo[100]; FILE *fp; int i,seguir; char text1[BUFSIZ],s1[BUFSIZ], *fin1, *ar_preg[500], preguntas[70000], *ar_resp[500]; char *ar_correctas[500]; FILE *fp1; // recibir nombre por dialogo if(pipe(pi)==-1) { puts("error en pipe"); exit(1); } pid=fork(); if(pid==-1) { puts("error en fork"); exit(1); } if(pid==0) { close(pi[0]); dup2(pi[1],1); *st='\0'; execlp("/usr/local/bin/greq","/usr/local/bin/greq","-t", "Confirmas? ", "-eNombre del TTrabajo", "-eTrabajo del alumno/a", NULL); printf("EEEEEEEEEEEEEEEEEEEEEEEEEE\n"); } close(pi[1]); s2[0]='\0'; n=read(pi[0],s2,BUFSIZ); s2[n]='\0'; if(*s2=='\0') exit(1); strcpy(resp_trabajo,"resp_"); p=strchr(s2,'\v'); *p='\0'; strcat(resp_trabajo,s2); strcpy(nombre,p+1); strcpy(arg_nombre,"a="); strcat(arg_nombre,nombre); if(pipe(pi)==-1) { puts("error en pipe"); exit(1); } pid=fork(); if(pid==-1) { puts("error en fork"); exit(1); } if(pid==0) { close(pi[0]); dup2(pi[1],1); sprintf(st,"-d%s",p); execlp("/usr/bin/awk","/usr/bin/awk","-f","muestra.awk", arg_nombre,resp_trabajo,NULL); printf("EEEEEEEEEEEEEEEEEEEEEEEEEE\n"); } close(pi[1]); s2[0]='\0'; n=read(pi[0],s2,BUFSIZ); printf("%s\n",s2); // //generar_preguntas_resp(ar_preg,ar_resp,preguntas,ar_correctas); if(pipe(pi)==-1) { puts("error en pipe"); exit(1); } pid=fork(); if(pid==-1) { puts("error en fork"); exit(1); } if(pid==0) { close(pi[0]); dup2(pi[1],1); sprintf(tit,"%s","Respuestas"); sprintf(tit2,"%s%80s %s %80s","-X","Respuestas de:",nombre," "); sprintf(tit0,"%s%80s %85s","-X","Preguntas"," "); execlp("/usr/local/bin/greq","/usr/local/bin/greq","-t",tit, tit2,"-z",s2,NULL); //"-X","-z",preguntas,NULL); puts("no ejecuto exec"); } close(pi[1]); s2[0]='\0'; n=read(pi[0],s2,BUFSIZ); s2[n]='\0'; //if(*s2=='\0') //exit(1); wait(&termina); if((termina>>8)==1) // ha cancelado { exit(1); } printf("SALGO\n"); exit(1); fp=fopen(resp_trabajo,"r"); if(fp==NULL) { puts("No puedo abrir file"); exit(1); } i=0; while(fin=fgets(s,BUFSIZ,fp)) { if(*s=='\n') break; } }
int job_start(struct job *j) { struct proc *p; struct redir *redir_iter; int pipey[2] = { -1, -1 }; #define REDIR(a, b) \ do{ \ if(a != b){ \ /* close b and copy a into b */ \ if(dup2(a, b) == -1) \ perror("dup2()"); \ if(close(a) == -1) \ perror("close()"); \ } \ }while(0) for(redir_iter = j->redir; redir_iter; redir_iter = redir_iter->next){ int fd; if(redir_iter->fname){ fd = open(redir_iter->fname, O_WRONLY | O_CREAT | O_TRUNC); /* FIXME: only out for now - need "<" and ">>" */ if(fd == -1){ fprintf(stderr, "ush: open %s: %s\n", redir_iter->fname, strerror(errno)); /* FIXME: close all other fds */ return 1; } }else{ fd = redir_iter->fd_out; } fprintf(stderr, "job_start(): REDIR(%d [%s], %d)\n", fd, redir_iter->fname, redir_iter->fd_in); REDIR(fd, redir_iter->fd_in); } j->proc->in = STDIN_FILENO; for(p = j->proc; p; p = p->next){ p->err = STDERR_FILENO; if(p->next){ if(pipe(pipey) < 0){ perror("pipe()"); goto bail; } p->out = pipey[1]; p->next->in = pipey[0]; }else{ p->out = STDOUT_FILENO; } /* TODO: cd, fg, rehash */ switch(p->pid = fork()){ case 0: p->pid = getpid(); REDIR(p->in, STDIN_FILENO); REDIR(p->out, STDOUT_FILENO); REDIR(p->err, STDERR_FILENO); #undef REDIR job_close_fds(j, p->next); proc_exec(p, j->gid); break; /* unreachable */ case -1: perror("fork()"); goto bail; default: if(interactive){ if(!j->gid) j->gid = p->pid; setpgid(p->pid, j->gid); } p->state = PROC_RUN; } } /* close our access to all these pipes */ job_close_fds(j, NULL); j->state = JOB_RUNNING; return 0; bail: fprintf(stderr, "warning: error starting job: %s\n", strerror(errno)); for(; p; p = p->next) p->state = PROC_FIN; job_close_fds(j, NULL); job_sig(j, SIGCONT); return 1; }
// code from http://www-theorie.physik.unizh.ch/~dpotter/howto/daemonize void daemon_start() { // already a daemon if(getppid() == 1) return; // 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_t pid = fork(); if (pid < 0) { fprintf(stderr, "unable to fork daemon, code=%d (%s)\n", errno, strerror(errno)); exit(1); } // 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(1); } // Create the pid file as the current user. int h = open(PID_FILE, O_RDWR|O_CREAT, 0640); if(h<0) { fprintf(stderr, "unable to create pid file %s, code=%d (%s)\n", PID_FILE, errno, strerror(errno)); exit(1); } char buf[10]; sprintf(buf, "%d", getpid()); write(h, buf, strlen(buf)); close(h); // At this point we are executing as the child process pid_t parent = getppid(); // 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,SIG_DFL); /* Die on SIGTERM */ /* Change the file mode mask */ umask(0); /* Create a new SID for the child process */ pid_t sid = setsid(); if (sid < 0) { fprintf(stderr, "unable to create a new session, code %d (%s)\n", errno, strerror(errno)); exit(1); } /* Change the current working directory. This prevents the current directory from being locked; hence not being able to remove it. */ if ((chdir("/")) < 0) { fprintf(stderr, "unable to change directory to %s, code %d (%s)\n", "/", errno, strerror(errno)); exit(EXIT_FAILURE); } /* Redirect standard files to /dev/null */ freopen( "/dev/null", "r", stdin); freopen( "/dev/null", "w", stdout); freopen( "/dev/null", "w", stderr); /* Tell the parent process that we are A-okay */ kill(parent, SIGUSR1); isDaemon = true; }
void die_you_gravy_sucking_pig_dog(void) { syslog(LOG_NOTICE, "%s by %s: %s", doreboot ? "reboot" : dohalt ? "halt" : "shutdown", whom, mbuf); (void)sleep(2); (void)printf("\r\nSystem shutdown time has arrived\007\007\r\n"); if (killflg) { (void)printf("\rbut you'll have to do it yourself\r\n"); finish(0); } if (dofast) doitfast(); #ifdef DEBUG if (doreboot) (void)printf("reboot"); else if (dohalt) (void)printf("halt"); if (nosync) (void)printf(" no sync"); if (dofast) (void)printf(" no fsck"); if (dodump) (void)printf(" with dump"); (void)printf("\nkill -HUP 1\n"); #else if (doreboot) { execle(_PATH_REBOOT, "reboot", "-l", (nosync ? "-n" : (dodump ? "-d" : NULL)), (dodump ? "-d" : NULL), (char *)NULL, (char *)NULL); syslog(LOG_ERR, "shutdown: can't exec %s: %m.", _PATH_REBOOT); warn(_PATH_REBOOT); } else if (dohalt) { execle(_PATH_HALT, "halt", "-l", (dopower ? "-p" : (nosync ? "-n" : (dodump ? "-d" : NULL))), (nosync ? "-n" : (dodump ? "-d" : NULL)), (dodump ? "-d" : NULL), (char *)NULL, (char *)NULL); syslog(LOG_ERR, "shutdown: can't exec %s: %m.", _PATH_HALT); warn(_PATH_HALT); } if (access(_PATH_RC, R_OK) != -1) { pid_t pid; struct termios t; int fd; switch ((pid = fork())) { case -1: break; case 0: if (revoke(_PATH_CONSOLE) == -1) perror("revoke"); if (setsid() == -1) perror("setsid"); fd = open(_PATH_CONSOLE, O_RDWR); if (fd == -1) perror("open"); dup2(fd, 0); dup2(fd, 1); dup2(fd, 2); if (fd > 2) close(fd); /* At a minimum... */ tcgetattr(0, &t); t.c_oflag |= (ONLCR | OPOST); tcsetattr(0, TCSANOW, &t); execl(_PATH_BSHELL, "sh", _PATH_RC, "shutdown", (char *)NULL); _exit(1); default: waitpid(pid, NULL, 0); } } (void)kill(1, SIGTERM); /* to single user */ #endif finish(0); }
int main(int argc, char *argv[]) { int arglen, ch, len, readstdin = 0; struct passwd *pw; char *p, *endp; pid_t forkpid; #ifndef DEBUG if (geteuid()) errx(1, "NOT super-user"); #endif while ((ch = getopt(argc, argv, "dfhknpr-")) != -1) switch (ch) { case '-': readstdin = 1; break; case 'd': dodump = 1; break; case 'f': dofast = 1; break; case 'h': dohalt = 1; break; case 'k': killflg = 1; break; case 'n': nosync = 1; break; case 'p': dopower = 1; break; case 'r': doreboot = 1; break; default: usage(); } argc -= optind; argv += optind; if (argc < 1) usage(); if (dofast && nosync) { (void)fprintf(stderr, "shutdown: incompatible switches -f and -n.\n"); usage(); } if (doreboot && dohalt) { (void)fprintf(stderr, "shutdown: incompatible switches -h and -r.\n"); usage(); } if (dopower && !dohalt) { (void)fprintf(stderr, "shutdown: switch -p must be used with -h.\n"); usage(); } getoffset(*argv++); if (*argv) { for (p = mbuf, len = sizeof(mbuf); *argv; ++argv) { arglen = strlen(*argv); if ((len -= arglen) <= 2) break; if (p != mbuf) *p++ = ' '; memcpy(p, *argv, arglen); p += arglen; } *p = '\n'; *++p = '\0'; } if (readstdin) { p = mbuf; endp = mbuf + sizeof(mbuf) - 2; for (;;) { if (!fgets(p, endp - p + 1, stdin)) break; for (; *p && p < endp; ++p) ; if (p == endp) { *p = '\n'; *++p = '\0'; break; } } } mbuflen = strlen(mbuf); if (offset) (void)printf("Shutdown at %.24s.\n", ctime(&shuttime)); else (void)printf("Shutdown NOW!\n"); if (!(whom = getlogin())) whom = (pw = getpwuid(getuid())) ? pw->pw_name : "???"; #ifdef DEBUG (void)putc('\n', stdout); #else (void)setpriority(PRIO_PROCESS, 0, PRIO_MIN); forkpid = fork(); if (forkpid == -1) err(1, "fork"); if (forkpid) { (void)printf("shutdown: [pid %ld]\n", (long)forkpid); exit(0); } setsid(); #endif openlog("shutdown", LOG_CONS, LOG_AUTH); loop(); /* NOTREACHED */ }
int main() { int sd; struct sigaction act; struct sockaddr_in self; bzero(&act, sizeof(act)); act.sa_handler = sig_handler; act.sa_flags = SA_NOCLDSTOP; sigaction(SIGCHLD, &act, 0); /*---Create new socket---*/ if ( (sd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) { perror("Socket"); exit(errno); } /* if ( setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, 0, 0) < 0 ) perror("SocketOpt");*/ /*---Initialize own server address---*/ bzero(&self, sizeof(self)); self.sin_family = AF_INET; self.sin_addr.s_addr = INADDR_ANY; self.sin_port = htons(MY_PORT); /*---Give the socket a "name" (set the IP and Port addresses)---*/ if ( bind(sd, (struct sockaddr*)&self, sizeof(self)) != 0 ) { perror("Bind"); abort(); } /*---Make the socket a "listening socket"---*/ if ( listen(sd, 20) != 0 ) { perror("Listen"); abort(); } /*---Forever...---*/ while (1) { static int client; int sd_copy, size; struct sockaddr_in client_info; /*---Accept client connection (creates a new communication port)---*/ size = sizeof(client_info); client = accept(sd, (struct sockaddr*)&client_info, &size); if ( client < 0 ) perror("Accept"); else { printf("Connected: %s:%d\n", inet_ntoa(client_info.sin_addr), ntohs(client_info.sin_port)); /*---Create child task to handle service---*/ if ( fork() != 0 ) { /*Parent*/ /*---The parent doesn't need the child's data connection---*/ close(client); } else { /*Child*/ /*---Child doesn't need access to request connection---*/ close(sd); /*---Map stdin, stdout and stderr to the data connection---*/ dup2(client, 0); dup2(client, 1); dup2(client, 2); /*---Call external program---*/ execl("/bin/ls", "/bin/ls", "-al", "/sbin", 0); } } } /*---Clean up (should never get here)---*/ close(sd); return 0; }
int main(int argc, char *argv[]) { char line[MAX_LINE_LENGTH]; // stores entire input string char *a[MAX_NUM_ARGS]; // a is an array of strings aka an array of char arrays char *token; char *exec; char *temp; int val, i, status; int last_val = 0; signal(SIGINT, handler); while(1) { /* Wait for input */ printf("MyShell>"); fgets(line, MAX_LINE_LENGTH, stdin); /* Parse input */ i = 0; token = strtok(line, " \t\n"); if(token!=NULL){ /* Check if the given command is internal one */ if (strncmp(token, "cd", 2) == 0) { token = strtok(NULL, " \t\n"); if(token!=NULL) { errno = 0; chdir(token); if(errno != 0) { printf("%s: No such file or directory\n", token); } } else { chdir(getenv("HOME")); } } else if (strncmp(token, "exit", 4) == 0) { token = strtok(NULL, " \t\n"); if(token!=NULL) { errno = 0; val = strtol(token, NULL, 10); if(errno != 0) { printf("Invalid exit value\n"); } else{ exit(val); } } else { exit(last_val); // LAST VAL NEVER GETTING SET } } else { /* launch executable */ a[0] = token; i = 1; token = strtok(NULL, " \t\n"); while(token != NULL) { a[i] = token; i++; token = strtok(NULL, " \t\n"); } a[i]=NULL; // child process if ((cid = fork()) == 0) { execvp(a[0], a); printf("Command not recognized\n"); exit(0); } // parent process else { wait(&status); } } } } return 0; }
int mount_syspuffs_parseargs(int argc, char *argv[], struct syspuffs_args *args, int *mntflags, char *canon_dev, char *canon_dir) { struct puffs_kargs *kargs = &args->us_kargs; int *pflags = &args->us_pflags; char comfd[16]; int sv[2]; size_t len; int rv; if (argc < 2) { return 1; } /* Create sucketpair for communication with the real file server */ if (socketpair(PF_LOCAL, SOCK_STREAM, 0, sv) == -1) err(1, "socketpair"); switch (fork()) { case 0: close(sv[1]); snprintf(comfd, sizeof(sv[0]), "%d", sv[0]); if (setenv("PUFFS_COMFD", comfd, 1) == -1) err(1, "setenv"); argv++; if (execvp(argv[0], argv) == -1) err(1, "execvp"); /*NOTREACHED*/ case -1: err(1, "fork"); /*NOTREACHED*/ default: close(sv[0]); break; } /* read args */ if (read(sv[1], &len, sizeof(len)) != sizeof(len)) err(1, "mp 1"); if (len > MAXPATHLEN) err(1, "mntpath > MAXPATHLEN"); if ((size_t)read(sv[1], canon_dir, len) != len) err(1, "mp 2"); if (read(sv[1], &len, sizeof(len)) != sizeof(len)) err(1, "fn 1"); if (len > MAXPATHLEN) err(1, "devpath > MAXPATHLEN"); if ((size_t)read(sv[1], canon_dev, len) != len) err(1, "fn 2"); if (read(sv[1], mntflags, sizeof(*mntflags)) != sizeof(*mntflags)) err(1, "mntflags"); if (read(sv[1], kargs, sizeof(*kargs)) != sizeof(*kargs)) err(1, "puffs_args"); if (read(sv[1], pflags, sizeof(*pflags)) != sizeof(*pflags)) err(1, "pflags"); /* XXX: some adjustments */ *pflags |= PUFFS_KFLAG_NOCACHE; *pflags &= ~PUFFS_FLAG_BUILDPATH; #if defined(COMPAT_50) rv = syspuffs_glueinit(sv[1], &kargs->pa_fd); #elif defined(HAVE_RUMP_PUB) rv = rump_pub_syspuffs_glueinit(sv[1], &kargs->pa_fd); #else rv = rump_syspuffs_glueinit(sv[1], &kargs->pa_fd); #endif assert(rv == 0); return 0; }
int main(int argc, char *argv[]) { char tempFile[strlen(argv[1]) + 1]; strcpy(tempFile, argv[1]); strcat(tempFile, "tempIndex.txt"); char* path = argv[0]; path[strlen(argv[0]) - 3] = '\0'; if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) perror("Error in function signal"); // number of files to concatenate and sort int n = strtol(argv[2], NULL, 10); // create and get file descriptor for tempFile int fd = open(tempFile, O_WRONLY | O_CREAT, 0750); if (fd == -1) perror("Error creating tempIndex"); int cenas = dup(STDOUT_FILENO); if (dup2(fd, STDOUT_FILENO) == -1) perror("Error duplicating descriptor"); // concatenate files int i, status; for (i = 1; i <= n; i++) { pid_t pid = fork(); if (pid == 0) // child { char fileName[20]; strcpy(fileName, "index"); char buffer[5]; sprintf(buffer, "%d", i); strcat(fileName, buffer); char file[strlen(path) + 1]; strcpy(file, path); strcat(fileName, ".txt"); strcat(file, fileName); execlp("cat", "cat", file, NULL); } else if (fork > 0) // parent wait(&status); else perror("Error creating fork"); } // sort files pid_t pid = fork(); if (pid == 0) // flag V to interpret numbers as integers and not as characters // flag f to not distinguish lower case characters from upper case characters // flag o to write the result into temp File instead of the standard output execlp("sort", "sort", "-V", "-f", "-o", tempFile, tempFile, NULL); else if (fork < 0) perror("Error creating fork"); wait(&status); dup2(cenas, STDOUT_FILENO); // create index char indexFile[strlen(argv[1]) + 1]; strcpy(indexFile, argv[1]); strcat(indexFile, "index.txt"); FILE* index = fopen(indexFile, "wa"); FILE* tempIndex = fopen(tempFile, "r"); char currentWord[20], location[10]; char previousWord[20] = ""; fputs("INDEX", index); while(fscanf(tempIndex, "%[^:]: %s\n", currentWord, location) == 2) { if (strcmp(previousWord, currentWord) == 0) fprintf(index, ", %s", location); else { strcpy(previousWord, currentWord); fprintf(index, "\n\n%s: %s", currentWord, location); } } if (remove(tempFile) != 0) perror("Error deleting file"); return 0; }
int main (int argc, char **argv) { pid_t child_id = OK; int i, status, isdf = 0; int distsw = 0, vecp = 0; char *cp, *dfolder = NULL, *dmsg = NULL; char *msg = NULL, **ap, **argp, backup[BUFSIZ]; char buf[BUFSIZ], **arguments, *vec[MAXARGS]; if (nmh_init(argv[0], 1)) { return 1; } arguments = getarguments (invo_name, argc, argv, 1); argp = arguments; vec[vecp++] = invo_name; vec[vecp++] = "-whom"; vec[vecp++] = "-library"; vec[vecp++] = getcpy (m_maildir ("")); /* Don't need to feed fileproc or mhlproc to post because it doesn't use them when used for whom. */ while ((cp = *argp++)) { if (*cp == '-') { switch (smatch (++cp, switches)) { case AMBIGSW: ambigsw (cp, switches); done (1); case UNKWNSW: adios (NULL, "-%s unknown", cp); case HELPSW: snprintf (buf, sizeof(buf), "%s [switches] [file]", invo_name); print_help (buf, switches, 1); done (0); case VERSIONSW: print_version(invo_name); done (0); case CHKSW: case NOCHKSW: case SNOOPSW: case SASLSW: case TLSSW: case INITTLSSW: case NTLSSW: vec[vecp++] = --cp; continue; case DRAFTSW: msg = draft; continue; case DFOLDSW: if (dfolder) adios (NULL, "only one draft folder at a time!"); if (!(cp = *argp++) || *cp == '-') adios (NULL, "missing argument to %s", argp[-2]); dfolder = path (*cp == '+' || *cp == '@' ? cp + 1 : cp, *cp != '@' ? TFOLDER : TSUBCWF); continue; case DMSGSW: if (dmsg) adios (NULL, "only one draft message at a time!"); if (!(dmsg = *argp++) || *dmsg == '-') adios (NULL, "missing argument to %s", argp[-2]); continue; case NDFLDSW: dfolder = NULL; isdf = NOTOK; continue; case ALIASW: case CLIESW: case SERVSW: case USERSW: case PORTSW: case SASLMECHSW: case MTSSW: vec[vecp++] = --cp; if (!(cp = *argp++) || *cp == '-') adios (NULL, "missing argument to %s", argp[-2]); vec[vecp++] = cp; continue; } } if (msg) adios (NULL, "only one draft at a time!"); else vec[vecp++] = msg = cp; } /* allow Aliasfile: profile entry */ if ((cp = context_find ("Aliasfile"))) { char *dp = NULL; for (ap = brkstring(dp = getcpy(cp), " ", "\n"); ap && *ap; ap++) { vec[vecp++] = "-alias"; vec[vecp++] = *ap; } } if (msg == NULL) { cp = getcpy (m_draft (dfolder, dmsg, 1, &isdf)); msg = vec[vecp++] = cp; } if ((cp = getenv ("mhdist")) && *cp && (distsw = atoi (cp)) && (cp = getenv ("mhaltmsg")) && *cp) { if (distout (msg, cp, backup) == NOTOK) done (1); vec[vecp++] = "-dist"; distsw++; } vec[vecp] = NULL; closefds (3); if (distsw) { for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++) sleep (5); } switch (distsw ? child_id : OK) { case NOTOK: advise (NULL, "unable to fork, so checking directly..."); case OK: execvp (postproc, vec); fprintf (stderr, "unable to exec "); perror (postproc); _exit (-1); default: SIGNAL (SIGHUP, SIG_IGN); SIGNAL (SIGINT, SIG_IGN); SIGNAL (SIGQUIT, SIG_IGN); SIGNAL (SIGTERM, SIG_IGN); status = pidwait(child_id, OK); (void) m_unlink (msg); if (rename (backup, msg) == NOTOK) adios (msg, "unable to rename %s to", backup); done (status); } return 0; /* dead code to satisfy the compiler */ }
bool ChopSeqsCommand::createProcesses(vector<linePair> lines, string filename, string outFasta, string outAccnos, string fastafileTemp) { try { int process = 1; bool wroteAccnos = false; vector<int> processIDS; vector<string> nonBlankAccnosFiles; bool recalc = false; #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix) //loop through and create all the processes you want while (process != processors) { pid_t pid = fork(); if (pid > 0) { processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later process++; }else if (pid == 0){ string fastafileTempThisProcess = fastafileTemp; if (fastafileTempThisProcess != "") { fastafileTempThisProcess = fastafileTempThisProcess + m->mothurGetpid(process) + ".temp"; } wroteAccnos = driver(lines[process], filename, outFasta + m->mothurGetpid(process) + ".temp", outAccnos + m->mothurGetpid(process) + ".temp", fastafileTempThisProcess); //pass numSeqs to parent ofstream out; string tempFile = fastafile + m->mothurGetpid(process) + ".bool.temp"; m->openOutputFile(tempFile, out); out << wroteAccnos << endl; out.close(); exit(0); }else { m->mothurOut("[ERROR]: unable to spawn the number of processes you requested, reducing number to " + toString(process) + "\n"); processors = process; for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); } //wait to die for (int i=0;i<processIDS.size();i++) { int temp = processIDS[i]; wait(&temp); } m->control_pressed = false; recalc = true; break; } } if (recalc) { //test line, also set recalc to true. //for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); } for (int i=0;i<processIDS.size();i++) { int temp = processIDS[i]; wait(&temp); } m->control_pressed = false; processors=3; m->mothurOut("[ERROR]: unable to spawn the number of processes you requested, reducing number to " + toString(processors) + "\n"); lines.clear(); vector<unsigned long long> positions = m->divideFile(filename, processors); for (int i = 0; i < (positions.size()-1); i++) { lines.push_back(linePair(positions[i], positions[(i+1)])); } processIDS.resize(0); process = 1; while (process != processors) { pid_t pid = fork(); if (pid > 0) { processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later process++; }else if (pid == 0){ string fastafileTempThisProcess = fastafileTemp; if (fastafileTempThisProcess != "") { fastafileTempThisProcess = fastafileTempThisProcess + m->mothurGetpid(process) + ".temp"; } wroteAccnos = driver(lines[process], filename, outFasta + m->mothurGetpid(process) + ".temp", outAccnos + m->mothurGetpid(process) + ".temp", fastafileTempThisProcess); //pass numSeqs to parent ofstream out; string tempFile = fastafile + m->mothurGetpid(process) + ".bool.temp"; m->openOutputFile(tempFile, out); out << wroteAccnos << endl; out.close(); exit(0); }else { m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); } exit(0); } } } //do your part wroteAccnos = driver(lines[0], filename, outFasta, outAccnos, fastafileTemp); //force parent to wait until all the processes are done for (int i=0;i<processIDS.size();i++) { int temp = processIDS[i]; wait(&temp); } if (wroteAccnos) { nonBlankAccnosFiles.push_back(outAccnos); } else { m->mothurRemove(outAccnos); } //remove so other files can be renamed to it //parent reads in and combine Filter info for (int i = 0; i < processIDS.size(); i++) { string tempFilename = fastafile + toString(processIDS[i]) + ".bool.temp"; ifstream in; m->openInputFile(tempFilename, in); bool temp; in >> temp; m->gobble(in); if (temp) { wroteAccnos = temp; nonBlankAccnosFiles.push_back(outAccnos + toString(processIDS[i]) + ".temp"); } else { m->mothurRemove((outAccnos + toString(processIDS[i]) + ".temp")); } in.close(); m->mothurRemove(tempFilename); } #else ////////////////////////////////////////////////////////////////////////////////////////////////////// //Windows version shared memory, so be careful when passing variables through the seqSumData struct. //Above fork() will clone, so memory is separate, but that's not the case with windows, //Taking advantage of shared memory to allow both threads to add info to vectors. ////////////////////////////////////////////////////////////////////////////////////////////////////// vector<chopData*> pDataArray; DWORD dwThreadIdArray[processors-1]; HANDLE hThreadArray[processors-1]; //Create processor worker threads. for( int i=0; i<processors-1; i++ ){ string extension = ""; if (i != 0) { extension = toString(i) + ".temp"; processIDS.push_back(i); } // Allocate memory for thread data. string fastafileTempThisProcess = fastafileTemp; if (fastafileTempThisProcess != "") { fastafileTempThisProcess = fastafileTempThisProcess + extension; } chopData* tempChop = new chopData(filename, (outFasta+extension), (outAccnos+extension), m, lines[i].start, lines[i].end, keep, countGaps, numbases, Short, keepN, qualfile, fastafileTempThisProcess); pDataArray.push_back(tempChop); //MyChopThreadFunction is in header. It must be global or static to work with the threads. //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier hThreadArray[i] = CreateThread(NULL, 0, MyChopThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]); } //do your part string fastafileTempThisProcess = fastafileTemp; if (fastafileTempThisProcess != "") { fastafileTempThisProcess = fastafileTempThisProcess + toString(processors-1) + ".temp"; } wroteAccnos = driver(lines[processors-1], filename, (outFasta + toString(processors-1) + ".temp"), (outAccnos + toString(processors-1) + ".temp"), fastafileTempThisProcess); processIDS.push_back(processors-1); //Wait until all threads have terminated. WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE); if (wroteAccnos) { nonBlankAccnosFiles.push_back(outAccnos); } else { m->mothurRemove(outAccnos); } //remove so other files can be renamed to it //Close all thread handles and free memory allocations. for(int i=0; i < pDataArray.size(); i++){ if (pDataArray[i]->wroteAccnos) { wroteAccnos = pDataArray[i]->wroteAccnos; nonBlankAccnosFiles.push_back(outAccnos + toString(processIDS[i]) + ".temp"); } else { m->mothurRemove((outAccnos + toString(processIDS[i]) + ".temp")); } //check to make sure the process finished if (pDataArray[i]->count != pDataArray[i]->end) { m->mothurOut("[ERROR]: process " + toString(i) + " only processed " + toString(pDataArray[i]->count) + " of " + toString(pDataArray[i]->end) + " sequences assigned to it, quitting. \n"); m->control_pressed = true; } CloseHandle(hThreadArray[i]); delete pDataArray[i]; } #endif for (int i = 0; i < processIDS.size(); i++) { if (fastafileTemp != "") { m->appendFiles((fastafileTemp + toString(processIDS[i]) + ".temp"), fastafileTemp); m->mothurRemove((fastafileTemp + toString(processIDS[i]) + ".temp")); } m->appendFiles((outFasta + toString(processIDS[i]) + ".temp"), outFasta); m->mothurRemove((outFasta + toString(processIDS[i]) + ".temp")); } if (nonBlankAccnosFiles.size() != 0) { m->renameFile(nonBlankAccnosFiles[0], outAccnos); for (int h=1; h < nonBlankAccnosFiles.size(); h++) { m->appendFiles(nonBlankAccnosFiles[h], outAccnos); m->mothurRemove(nonBlankAccnosFiles[h]); } }else { //recreate the accnosfile if needed ofstream out; m->openOutputFile(outAccnos, out); out.close(); } return wroteAccnos; } catch(exception& e) { m->errorOut(e, "ChopSeqsCommand", "createProcesses"); exit(1); } }
void sbrktest(void) { int fds[2], pid, pids[10], ppid; char *a, *b, *c, *lastaddr, *oldbrk, *p, scratch; uint amt; printf(stdout, "sbrk test\n"); oldbrk = sbrk(0); // can one sbrk() less than a page? a = sbrk(0); int i; for(i = 0; i < 5000; i++){ b = sbrk(1); if(b != a){ printf(stdout, "sbrk test failed %d %x %x\n", i, a, b); exit(); } *b = 1; a = b + 1; } pid = fork(); if(pid < 0){ printf(stdout, "sbrk test fork failed\n"); exit(); } c = sbrk(1); c = sbrk(1); if(c != a + 1){ printf(stdout, "sbrk test failed post-fork\n"); exit(); } if(pid == 0) exit(); wait(); // can one grow address space to something big? #define BIG (100*1024*1024) a = sbrk(0); amt = (BIG) - (uint)a; p = sbrk(amt); if (p != a) { printf(stdout, "sbrk test failed to grow big address space; enough phys mem?\n"); exit(); } lastaddr = (char*) (BIG-1); *lastaddr = 99; // can one de-allocate? a = sbrk(0); c = sbrk(-4096); if(c == (char*)0xffffffff){ printf(stdout, "sbrk could not deallocate\n"); exit(); } c = sbrk(0); if(c != a - 4096){ printf(stdout, "sbrk deallocation produced wrong address, a %x c %x\n", a, c); exit(); } // can one re-allocate that page? a = sbrk(0); c = sbrk(4096); if(c != a || sbrk(0) != a + 4096){ printf(stdout, "sbrk re-allocation failed, a %x c %x\n", a, c); exit(); } if(*lastaddr == 99){ // should be zero printf(stdout, "sbrk de-allocation didn't really deallocate\n"); exit(); } a = sbrk(0); c = sbrk(-(sbrk(0) - oldbrk)); if(c != a){ printf(stdout, "sbrk downsize failed, a %x c %x\n", a, c); exit(); } // can we read the kernel's memory? for(a = (char*)(KERNBASE); a < (char*) (KERNBASE+2000000); a += 50000){ ppid = getpid(); pid = fork(); if(pid < 0){ printf(stdout, "fork failed\n"); exit(); } if(pid == 0){ printf(stdout, "oops could read %x = %x\n", a, *a); kill(ppid); exit(); } wait(); } // if we run the system out of memory, does it clean up the last // failed allocation? if(pipe(fds) != 0){ printf(1, "pipe() failed\n"); exit(); } for(i = 0; i < sizeof(pids)/sizeof(pids[0]); i++){ if((pids[i] = fork()) == 0){ // allocate a lot of memory sbrk(BIG - (uint)sbrk(0)); write(fds[1], "x", 1); // sit around until killed for(;;) sleep(1000); } if(pids[i] != -1) read(fds[0], &scratch, 1); } // if those failed allocations freed up the pages they did allocate, // we'll be able to allocate here c = sbrk(4096); for(i = 0; i < sizeof(pids)/sizeof(pids[0]); i++){ if(pids[i] == -1) continue; kill(pids[i]); wait(); } if(c == (char*)0xffffffff){ printf(stdout, "failed sbrk leaked memory\n"); exit(); } if(sbrk(0) > oldbrk) sbrk(-(sbrk(0) - oldbrk)); printf(stdout, "sbrk test OK\n"); }
// Execute cmd. Never returns. void runcmd(struct cmd *cmd) { int p[2], r; struct execcmd *ecmd; struct pipecmd *pcmd; struct redircmd *rcmd; if(cmd == 0) exit(0); switch(cmd->type) { default: fprintf(stderr, "unknown runcmd\n"); exit(-1); case ' ': ecmd = (struct execcmd*)cmd; if(ecmd->argv[0] == 0) exit(0); char abscmd[CMD_MAXLEN]; if(NULL == searchfile(abscmd, CMD_MAXLEN, ecmd->argv[0], F_OK|R_OK|X_OK)) { fprintf(stderr, "file not exist or permission denied\n"); exit(-1); } if(-1 == execv(abscmd, ecmd->argv) ) { fprintf(stderr, "exec failed\n"); } break; case '>': case '<': rcmd = (struct redircmd*)cmd; char absfile[CMD_MAXLEN]; memset(absfile, 0, sizeof(absfile)); int newfd; if(rcmd->fd == 0) { if(-1 == access(rcmd->file, F_OK|R_OK)) { newfd= open(rcmd->file, rcmd->mode); } else { if(NULL == searchfile(absfile, sizeof(absfile), rcmd->file, F_OK|R_OK)) { die("redirction file not exist or permission denied"); } else { newfd= open(absfile, rcmd->mode); } } } else { if('/' == (rcmd->file)[0]) { newfd= open(rcmd->file, rcmd->mode); } else { char* pwd= getenv("PWD"); strcat(absfile, pwd); strncat(absfile, "/", 1); strncat(absfile, rcmd->file, sizeof(rcmd->file)); newfd= open(absfile, rcmd->mode, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP); } } int bakfd= dup(rcmd->fd); dup2(newfd, rcmd->fd); close(newfd); runcmd(rcmd->cmd); dup2(bakfd, rcmd->fd); break; case '|': pcmd = (struct pipecmd*)cmd; int pipes[2]; if(-1 == pipe(pipes)) { die("pipe"); } int pid= fork(); if(-1 == pid) { die("fork"); } if(0 == pid) { // left cmd dup2(pipes[1], STDOUT_FILENO); close(pipes[0]); runcmd(pcmd->left); } else { // right cmd dup2(pipes[0], STDIN_FILENO); close(pipes[1]); waitpid(pid); runcmd(pcmd->right); } break; } exit(0); }
// two processes write two different files at the same // time, to test block allocation. void twofiles(void) { int fd, pid, i, j, n, total; char *fname; printf(1, "twofiles test\n"); unlink("f1"); unlink("f2"); pid = fork(); if(pid < 0){ printf(1, "fork failed\n"); exit(); } fname = pid ? "f1" : "f2"; fd = open(fname, O_CREATE | O_RDWR); if(fd < 0){ printf(1, "create failed\n"); exit(); } memset(buf, pid?'p':'c', 512); for(i = 0; i < 12; i++){ if((n = write(fd, buf, 500)) != 500){ printf(1, "write failed %d\n", n); exit(); } } close(fd); if(pid) wait(); else exit(); for(i = 0; i < 2; i++){ fd = open(i?"f1":"f2", 0); total = 0; while((n = read(fd, buf, sizeof(buf))) > 0){ for(j = 0; j < n; j++){ if(buf[j] != (i?'p':'c')){ printf(1, "wrong char\n"); exit(); } } total += n; } close(fd); if(total != 12*500){ printf(1, "wrong length %d\n", total); exit(); } } unlink("f1"); unlink("f2"); printf(1, "twofiles ok\n"); }
int _tmain(int argc, TCHAR** argv) { if(argc==1) { _tprintf(_T("\nDo you want to run tests from a folder cotaining Chineese characters to test UNICODE compatibility (y/n)?\n")); _tprintf(_T("Your choice > ")); TCHAR szAnswer[1024]=_T(""); #if _MSC_VER>=1400 _getts_s(szAnswer, 1024); #else _getts(szAnswer); #endif if(_tcscmp(szAnswer, _T("y"))==0 || _tcscmp(szAnswer, _T("Y"))==0) { // Relaunch this process from another working directory containing UNICODE symbols in path. // This is needed to test all functionality on UNICODE compatibility. g_bRunningFromUNICODEFolder = TRUE; } if(g_bRunningFromUNICODEFolder) { _tprintf(_T("Launching tests in another process:\n")); if(g_bRunningFromUNICODEFolder) _tprintf(_T(" - with working directory having UNICODE symbols in path\n")); return fork(); } } else { int argnum; for(argnum=1; argnum<argc; argnum++) { TCHAR* szArg = argv[argnum]; if(_tcscmp(szArg, _T("/unicode"))==0) g_bRunningFromUNICODEFolder = TRUE; } } printf("\n=== Automated tests for CrashRpt v.%d.%d.%d ===\n\n", CRASHRPT_VER/1000, (CRASHRPT_VER%1000)/100, (CRASHRPT_VER%1000)%100); printf("The list of avaliable test suites:\n"); // Print the list of test suites std::map<std::string, std::string>::iterator siter; for(siter=g_pTestSuiteList->begin(); siter!=g_pTestSuiteList->end(); siter++) { printf(" - %s : %s\n", siter->first.c_str(), siter->second.c_str()); } printf("\nEnter which test suites to run (separate names by space) or enter empty line to run all test suites.\n"); printf("Your choice > "); char szSuiteList[1024]=""; #if _MSC_VER>=1400 gets_s(szSuiteList, 1024); #else gets(szSuiteList); #endif // Create the list of test suites to run std::string sSuiteList = szSuiteList; std::vector<std::string> aTokens = explode(sSuiteList); std::set<std::string> aTestSuitesToRun; size_t i; for(i=0; i<aTokens.size(); i++) aTestSuitesToRun.insert(aTokens[i]); // Determine how many tests to run size_t nTestsToRun = 0; if(aTestSuitesToRun.size()==0) { nTestsToRun = g_pTestList->size(); } else { std::map<std::string, PFNTEST>::iterator iter; for(iter=g_pTestList->begin(); iter!=g_pTestList->end(); iter++) { std::string sName = iter->first; size_t pos = sName.find(':'); std::string sTestSuite = sName.substr(0, pos); std::set<std::string>::iterator sit = aTestSuitesToRun.find(sTestSuite); if(sit!=aTestSuitesToRun.end()) { nTestsToRun++; } } } if(nTestsToRun==0) { printf("\nNo tests selected, exiting.\n"); return 0; } printf("\nRunning tests...\n"); // Walk through all registered test and run each one std::map<std::string, PFNTEST>::iterator iter; int n = 1; for(iter=g_pTestList->begin(); iter!=g_pTestList->end(); iter++) { std::string sName = iter->first; size_t pos = sName.find(':'); std::string sTestSuite = sName.substr(0, pos); std::set<std::string>::iterator sit = aTestSuitesToRun.find(sTestSuite); if(aTestSuitesToRun.size()==0 || sit!=aTestSuitesToRun.end()) { printf("- %d/%d: %s ...\n", n, nTestsToRun, iter->first.c_str()); n++; iter->second(); } } printf("\n=== Summary ===\n\n"); // Print all errors (if exist) if(g_pErrorList!=NULL) { size_t i; for(i=0; i<g_pErrorList->size(); i++) { printf("Error %d: %s\n", i, (*g_pErrorList)[i].c_str()); } } printf("\n Test count: %d\n", nTestsToRun); size_t nErrorCount = g_pErrorList!=NULL?g_pErrorList->size():0; printf(" Tests passed: %d\n", nTestsToRun-nErrorCount); printf(" Tests failed: %d\n", nErrorCount); // Wait for key press _getch(); // Clean up if(g_pTestSuiteList!=NULL) delete g_pTestSuiteList; if(g_pTestList!=NULL) delete g_pTestList; if(g_pErrorList) delete g_pErrorList; // Return non-zero value if there were errors return nErrorCount==0?0:1; }
// two processes create and delete different files in same directory void createdelete(void) { enum { N = 20 }; int pid, i, fd; char name[32]; printf(1, "createdelete test\n"); pid = fork(); if(pid < 0){ printf(1, "fork failed\n"); exit(); } name[0] = pid ? 'p' : 'c'; name[2] = '\0'; for(i = 0; i < N; i++){ name[1] = '0' + i; fd = open(name, O_CREATE | O_RDWR); if(fd < 0){ printf(1, "create failed\n"); exit(); } close(fd); if(i > 0 && (i % 2 ) == 0){ name[1] = '0' + (i / 2); if(unlink(name) < 0){ printf(1, "unlink failed\n"); exit(); } } } if(pid==0) exit(); else wait(); for(i = 0; i < N; i++){ name[0] = 'p'; name[1] = '0' + i; fd = open(name, 0); if((i == 0 || i >= N/2) && fd < 0){ printf(1, "oops createdelete %s didn't exist\n", name); exit(); } else if((i >= 1 && i < N/2) && fd >= 0){ printf(1, "oops createdelete %s did exist\n", name); exit(); } if(fd >= 0) close(fd); name[0] = 'c'; name[1] = '0' + i; fd = open(name, 0); if((i == 0 || i >= N/2) && fd < 0){ printf(1, "oops createdelete %s didn't exist\n", name); exit(); } else if((i >= 1 && i < N/2) && fd >= 0){ printf(1, "oops createdelete %s did exist\n", name); exit(); } if(fd >= 0) close(fd); } for(i = 0; i < N; i++){ name[0] = 'p'; name[1] = '0' + i; unlink(name); name[0] = 'c'; unlink(name); } printf(1, "createdelete ok\n"); }
main() { int sockfd , clisockfd; unsigned int clilen; int childpid; struct sockaddr_in serv_addr,cli_addr; #ifdef LPR_with_ASUS//JY1112 int LPRflag = 0; fd_set rfds, afds; int nfds,nfds1; int sockfd_ASUS; unsigned int clilen_ASUS; int childpid_ASUS; struct sockaddr_in serv_addr_ASUS,cli_addr_ASUS; #endif #ifdef Raw_Printing_with_ASUS //Lisa int netfd, fd, clientlen, one = 1; struct sockaddr_in netaddr, client; #endif //Initial the server the not busy lptstatus.busy = FALSE; //Setup the signal handler signal(SIGCLD, sig_child); signal(SIGINT, sig_cleanup); signal(SIGQUIT, sig_cleanup); signal(SIGKILL, sig_cleanup); signal(SIGUSR2, sig_remove);//JY1110 if((sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0 ) { perror("can't open stream socket:"); exit(0); } bzero((char *)&serv_addr , sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(PNT_SVR_PORT_LPR); if(bind(sockfd,(struct sockaddr *)&serv_addr , sizeof(serv_addr)) < 0 ) { perror("can't bind:"); exit(0); } /*JY1111*/ int windowsize=2920; setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, (char *)&windowsize, sizeof(windowsize)); #if 1 int currentpid=getpid(); FILE *pidfileread; if((pidfileread=fopen("/var/run/lpdparent.pid", "r")) == NULL) { pidfileread=fopen("/var/run/lpdparent.pid", "w"); fprintf(pidfileread, "%d", currentpid); fclose(pidfileread); } else { printf("another lpd daemon exists!!\n"); fclose(pidfileread); exit(0); } #endif /*JY1110 int testusb = 0; testusb = check_par_usb_prn(); if(testusb){ printf("USB\n");//JY1112delete fd_print=open("/dev/usb/lp0", O_RDWR); } else{ printf("PARALLEL\n");//JY1112delete fd_print=open("/dev/lp0", O_RDWR); } checkstatus_usb_par(); close(fd_print); 111111*/ listen(sockfd , 15); #ifdef Raw_Printing_with_ASUS //Lisa if ((netfd = socket(AF_INET, SOCK_STREAM, IPPROTO_IP)) < 0) { // syslog(LOGOPTS, "socket: %m\n"); exit(1); } if (setsockopt(netfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0) { // syslog(LOGOPTS, "setsocketopt: %m\n"); exit(1); } netaddr.sin_port = htons(BASEPORT); netaddr.sin_addr.s_addr = htonl(INADDR_ANY); memset(netaddr.sin_zero, 0, sizeof(netaddr.sin_zero)); if (bind(netfd, (struct sockaddr*) &netaddr, sizeof(netaddr)) < 0) { // syslog(LOGOPTS, "bind: %m\n"); exit(1); } if (listen(netfd, 5) < 0) { // syslog(LOGOPTS, "listen: %m\n"); exit(1); } //clientlen = sizeof(client); //memset(&client, 0, sizeof(client)); #endif #ifdef LPR_with_ASUS//JY1112 if((sockfd_ASUS = socket(AF_INET,SOCK_STREAM,0)) < 0 ) { perror("can't open stream socket:"); exit(0); } bzero((char *)&serv_addr_ASUS , sizeof(serv_addr_ASUS)); serv_addr_ASUS.sin_family = AF_INET; serv_addr_ASUS.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr_ASUS.sin_port = htons(PNT_SVR_PORT_ASUS); if(bind(sockfd_ASUS,(struct sockaddr *)&serv_addr_ASUS , sizeof(serv_addr_ASUS)) < 0 ) { perror("can't bind:"); exit(0); } setsockopt(sockfd_ASUS, SOL_SOCKET, SO_RCVBUF, (char *)&windowsize, sizeof(windowsize)); listen(sockfd_ASUS , 15); /*set the fds*/ nfds1=MAX(sockfd, sockfd_ASUS); #ifdef Raw_Printing_with_ASUS //Lisa nfds=MAX(nfds1, netfd); #endif FD_ZERO(&afds); #endif while(TRUE) { #ifdef Raw_Printing_with_ASUS //Lisa FD_SET(netfd, &afds); #endif #ifdef LPR_with_ASUS//JY1112 FD_SET(sockfd, &afds); FD_SET(sockfd_ASUS, &afds); int err_select;//JY1113 memcpy(&rfds, &afds, sizeof(rfds)); if((err_select=select(nfds+1, &rfds, (fd_set *)0, (fd_set *)0, (struct timeval *)0 )) < 0) { //JY1120 printf("select error on sockfd: error=%d\n", errno); /**/ // printf("sockfd_FD_ISSET=%d\n", FD_ISSET(sockfd, &rfds)); //JY1120 printf("sockfd_ASUS FD_ISSET=%d\n", FD_ISSET(sockfd_ASUS, &rfds)); /**/ // if(errno != 4)//JY1113: delete continue; } #endif clilen = sizeof(cli_addr); if (busy == FALSE) //Add by Lisa { busy = TRUE; // Add by Lisa #ifdef LPR_with_ASUS//JY1112 if(FD_ISSET(sockfd, &rfds)) { LPRflag = 1; clisockfd = accept(sockfd,(struct sockaddr *)&cli_addr, &clilen); //JY1120 printf("LPR sock received...\n");//JY1114: delete } else if(FD_ISSET(sockfd_ASUS, &rfds)) { LPRflag = 0; clisockfd = accept(sockfd_ASUS,(struct sockaddr *)&cli_addr, &clilen); //JY1120 printf("ASUSRemote port sock receved...\n");//JY1114: delete } #ifdef Raw_Printing_with_ASUS //Lisa else if(FD_ISSET(netfd, &rfds)) { LPRflag = 2; clisockfd = accept(netfd, (struct sockaddr*) &cli_addr, &clilen); printf("Raw Printing sock received...\n"); } #endif else { perror("lpr: no data received..."); continue; } #else clisockfd = accept(sockfd,(struct sockaddr *)&cli_addr, &clilen); #endif strcpy(clientaddr , inet_ntoa(cli_addr.sin_addr)); if(clisockfd < 0) { perror("accept error:"); continue; } //remark PRINT("Accept OK ,client address -- %s\n",inet_ntoa(cli_addr.sin_addr)); if( (childpid = fork() ) < 0) { perror("fork error:"); } else if(childpid == 0) { printf("child start\n"); //child process starts here //#ifdef LPR_SUPPORT //JY1120 printf("LPR process....\n"); #ifdef LPR_with_ASUS//JY1114 //JY1120 printf("lptstatus.busy=%s\n", lptstatus.busy);//JY1114 //JY1120 printf("lptstatus.pid=%d\n", lptstatus.pid);//JY1114 if(LPRflag == 1) { printf("LPRflag_remote=%d \n",LPRflag); processReq_LPR(clisockfd); } #ifdef Raw_Printing_with_ASUS //Lisa else if (LPRflag == 2) { printf("LPRflag_raw=%d \n",LPRflag); processReq_Raw(clisockfd); } #endif else #endif { printf("LPRflag_LPR=%d \n",LPRflag); processReq(clisockfd); } //#else // processReq(clisockfd); //#endif //PRINT("client exit\n"); if(LPRflag == 1) printf("LPR client exit\n");//JY1113delete else if (LPRflag == 2) printf("Raw Printing client exit\n"); else printf("ASUS Remote client exit\n");//JY1113delete // check_prn_status(ONLINE, ""); close(sockfd);// close(sockfd_ASUS);// exit(0); } //parents process goes on here //remark PRINT("fork -- childpid %d\n",childpid); if(lptstatus.busy == FALSE) { //someone is using the printer now //lptstatus.busy = TRUE; //record the infomation of the client process strcpy(lptstatus.addr , inet_ntoa(cli_addr.sin_addr)); lptstatus.pid = childpid; } } //PRINT("lptstatus.addr %s\n",lptstatus.addr); close(clisockfd); } }
// test concurrent create/link/unlink of the same file void concreate(void) { char file[3]; int i, pid, n, fd; char fa[40]; struct { ushort inum; char name[14]; } de; printf(1, "concreate test\n"); file[0] = 'C'; file[2] = '\0'; for(i = 0; i < 40; i++){ file[1] = '0' + i; unlink(file); pid = fork(); if(pid && (i % 3) == 1){ link("C0", file); } else if(pid == 0 && (i % 5) == 1){ link("C0", file); } else { fd = open(file, O_CREATE | O_RDWR); if(fd < 0){ printf(1, "concreate create %s failed\n", file); exit(); } close(fd); } if(pid == 0) exit(); else wait(); } memset(fa, 0, sizeof(fa)); fd = open(".", 0); n = 0; while(read(fd, &de, sizeof(de)) > 0){ if(de.inum == 0) continue; if(de.name[0] == 'C' && de.name[2] == '\0'){ i = de.name[1] - '0'; if(i < 0 || i >= sizeof(fa)){ printf(1, "concreate weird file %s\n", de.name); exit(); } if(fa[i]){ printf(1, "concreate duplicate file %s\n", de.name); exit(); } fa[i] = 1; n++; } } close(fd); if(n != 40){ printf(1, "concreate not enough files in directory listing\n"); exit(); } for(i = 0; i < 40; i++){ file[1] = '0' + i; pid = fork(); if(pid < 0){ printf(1, "fork failed\n"); exit(); } if(((i % 3) == 0 && pid == 0) || ((i % 3) == 1 && pid != 0)){ close(open(file, 0)); close(open(file, 0)); close(open(file, 0)); close(open(file, 0)); } else { unlink(file); unlink(file); unlink(file); unlink(file); } if(pid == 0) exit(); else wait(); } printf(1, "concreate ok\n"); }
/* The main test function. */ int main(int argc, char * argv[]) { int ret, param, status; pid_t child, ctl; struct sched_param sp; /* Initialize output */ output_init(); /* Change process policy and parameters */ sp.sched_priority = param = sched_get_priority_max(POLICY); if (sp.sched_priority == -1) { UNRESOLVED(errno, "Failed to get max priority value"); } ret = sched_setscheduler(0, POLICY, &sp); if (ret == -1) { UNRESOLVED(errno, "Failed to change process scheduling policy"); } /* Create the child */ child = fork(); if (child == -1) { UNRESOLVED(errno, "Failed to fork"); } /* child */ if (child == 0) { /* Check the scheduling policy */ ret = sched_getscheduler(0); if (ret == -1) { UNRESOLVED(errno, "Failed to read scheduling policy in child"); } if (ret != POLICY) { FAILED("The scheduling policy was not inherited"); } ret = sched_getparam(0, &sp); if (ret != 0) { UNRESOLVED(errno, "Failed to read scheduling parameter in child"); } if (sp.sched_priority != param) { FAILED("The scheduling parameter was not inherited"); } /* We're done */ exit(PTS_PASS); } /* Parent joins the child */ ctl = waitpid(child, &status, 0); if (ctl != child) { UNRESOLVED(errno, "Waitpid returned the wrong PID"); } if (!WIFEXITED(status) || (WEXITSTATUS(status) != PTS_PASS)) { FAILED("Child exited abnormally"); } /* Test passed */ #if VERBOSE > 0 output("Test passed\n"); #endif PASSED; }
void daemonize(const char *cmd) { int i, fd0, fd1, fd2; pid_t pid; struct rlimit rl; struct sigaction sa; /* * Clear file creation mask. */ umask(0); /* * Get maximum number of file descriptors. */ if (getrlimit(RLIMIT_NOFILE, &rl) < 0) { fprintf(stderr, "%s: can’t get file limit\n", cmd); exit(1); } /* * Become a session leader to lose controlling TTY. */ if ((pid = fork()) < 0) { fprintf(stderr, "fork error\n"); exit(1); } else if (pid != 0) { // parent exit(0); } setsid(); /* * Ensure future opens won’t allocate controlling TTYs. */ sa.sa_handler = SIG_IGN; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; if (sigaction(SIGHUP, &sa, NULL) < 0) { fprintf(stderr, "can't ignore SIGHUP\n"); exit(0); } if ((pid = fork()) < 0) { fprintf(stderr, "fork error\n"); exit(1); } else if (pid != 0) { // parent exit(0); } /* * Change the current working directory to the root so * we won’t prevent file systems from being unmounted. */ if (chdir("/") < 0) { fprintf(stderr, "%s: can’t change directory to /\n", cmd); exit(0); } /* * Close all open file descriptors. */ if (rl.rlim_max == RLIM_INFINITY) { rl.rlim_max = 1024; } for (i = 0; i < rl.rlim_max; i++) { close(i); } /* * Attach file descriptors 0, 1, and 2 to /dev/null. */ fd0 = open("/dev/null", O_RDWR); fd1 = dup(0); fd2 = dup(0); /* * Initialize the log file. */ openlog(cmd, LOG_CONS, LOG_DAEMON); if (fd0 != 0 || fd1 != 1 || fd2 != 2) { syslog(LOG_ERR, "unexpected file descriptors %d %d %d", fd0, fd1, fd2); exit(1); } }
R_API int r_sys_cmd_str_full(const char *cmd, const char *input, char **output, int *len, char **sterr) { char buffer[1024], *outputptr = NULL; char *inputptr = (char *)input; int pid, bytes = 0, status; int sh_in[2], sh_out[2], sh_err[2]; if (len) *len = 0; if (pipe (sh_in)) return R_FALSE; if (output) { if (pipe (sh_out)) { close (sh_in[0]); close (sh_in[1]); close (sh_out[0]); close (sh_out[1]); return R_FALSE; } } if (pipe (sh_err)) { close (sh_in[0]); close (sh_in[1]); return R_FALSE; } switch ((pid=fork ())) { case -1: return R_FALSE; case 0: dup2 (sh_in[0], 0); close (sh_in[0]); close (sh_in[1]); if (output) { dup2 (sh_out[1], 1); close (sh_out[0]); close (sh_out[1]); } if (sterr) dup2 (sh_err[1], 2); else close (2); close (sh_err[0]); close (sh_err[1]); exit (r_sandbox_system (cmd, 0)); default: outputptr = strdup (""); if (!outputptr) return R_FALSE; if (sterr) { *sterr = strdup (""); if (!*sterr) { free (outputptr); return R_FALSE; } } if (output) close (sh_out[1]); close (sh_err[1]); close (sh_in[0]); if (!inputptr || !*inputptr) close (sh_in[1]); for (;;) { fd_set rfds, wfds; int nfd; FD_ZERO (&rfds); FD_ZERO (&wfds); if (output) FD_SET (sh_out[0], &rfds); if (sterr) FD_SET (sh_err[0], &rfds); if (inputptr && *inputptr) FD_SET (sh_in[1], &wfds); memset (buffer, 0, sizeof (buffer)); nfd = select (sh_err[0] + 1, &rfds, &wfds, NULL, NULL); if (nfd < 0) break; if (output && FD_ISSET (sh_out[0], &rfds)) { if ((bytes = read (sh_out[0], buffer, sizeof (buffer)-1)) == 0) break; buffer[sizeof(buffer) - 1] = '\0'; if (len) *len += bytes; outputptr = r_str_concat (outputptr, buffer); } else if (FD_ISSET (sh_err[0], &rfds) && sterr) { if (read (sh_err[0], buffer, sizeof (buffer)-1) == 0) break; buffer[sizeof(buffer) - 1] = '\0'; *sterr = r_str_concat (*sterr, buffer); } else if (FD_ISSET (sh_in[1], &wfds) && inputptr && *inputptr) { bytes = write (sh_in[1], inputptr, strlen (inputptr)); inputptr += bytes; if (!*inputptr) { close (sh_in[1]); /* If neither stdout nor stderr should be captured, * abort now - nothing more to do for select(). */ if (!output && !sterr) break; } } } if (output) close (sh_out[0]); close (sh_err[0]); close (sh_in[1]); waitpid (pid, &status, 0); if (status != 0) { char *escmd = r_str_escape (cmd); eprintf ("%s: failed command '%s'\n", __func__, escmd); free (escmd); return R_FALSE; } if (output) *output = outputptr; else free (outputptr); return R_TRUE; } return R_FALSE; }
void press_key(int fd, int key, int value) { if (key>0) { static struct input_event event={ .type = EV_KEY }; const static struct input_event syn_event={ .type = EV_SYN, .code = SYN_REPORT, .value = 0 }; event.code=key; event.value=value; write(fd, &event, sizeof(event)); write(fd, &syn_event, sizeof(event)); } } int main(int argc, char **argv) { int rfd=0, wfd=0, res=0; unsigned char buf[16]; typedef unsigned long long keystate; int opt; unsigned char do_fork=1; while ((opt = getopt(argc, argv, "f")) != -1) { switch (opt) { case 'f': do_fork = 0; break; default: fprintf (stderr, "Invalid option: -%c\n", opt); return 1; } } if (argc > optind+1) { fprintf (stderr, "Usage: %s [device]\n", *argv); exit(1); } if (argc == optind+1) { if ((rfd = open (argv[optind], O_RDONLY)) <= 0) { perror (argv[optind]); return 1; } } else { rfd=open_kb(); } wfd=open_uinput(); if (rfd <= 0) { puts ("failed to find keyboard"); return 1; } if (do_fork) { switch(fork()) { case -1: perror ("fork"); return 1; case 0: break; default: return 0; } } keystate prev=0, cur=0; while ((res = read(rfd, buf, 16)) > 0) { cur=*((keystate*)(buf+2)); if (cur && (cur != prev)) { keystate cur_new = cur & (cur ^ prev); keystate cur_old = prev & (cur ^ prev); if (cur_new || cur_old) { int i; keystate b; for (i=0, b=1; positions[i]!=0; ++i, b<<=1) { if (cur_old & b) press_key(wfd,positions[i], 0); else if (cur_new & b) press_key(wfd,positions[i], 1); } prev=cur; } } } close(rfd); ioctl(wfd, UI_DEV_DESTROY); close(wfd); return 0; }