bool Log_Writer::_write(char *_pbuffer, int len) { if(0 != access(m_filelocation, W_OK)) { pthread_mutex_lock(&m_mutex); //锁内校验 access 看是否在等待锁过程中被其他线程loginit了 避免多线程多次close 和init if(0 != access(m_filelocation, W_OK)) { logclose(); loginit(m_system_level, m_filelocation, m_isappend, m_issync); } pthread_mutex_unlock(&m_mutex); } if(1 == fwrite(_pbuffer, len, 1, fp)) //only write 1 item { if(m_issync) fflush(fp); *_pbuffer='\0'; } else { int x = errno; fprintf(stderr, "Failed to write to logfile. errno:%s message:%s", strerror(x), _pbuffer); return false; } return true; }
int init_obj(void) { if (initSocket()) return -1; char szFilePath[256] = {0}; char szFileName[256] = {0}; char szLogFilePath[256] = {0}; if (getExePath(szFilePath, szFileName, 256)) return -1; sprintf(szLogFilePath, "%s/%s", szFilePath, "log.dat"); #ifdef _MYDEBUG if (loginit(szLogFilePath, LOG_INFO)) return -1; #else if (loginit(szLogFilePath, LOG_WARNING)) return -1; #endif if (rdb_init()) { logout(LOG_EMERGENCY, "Failed to init protocol", __FILE__, __LINE__); return -1; } if (pushOut_init()) { logout(LOG_ERR, "Failed to init push out", __FILE__, __LINE__); return -1; } if (ptl_init()) { logout(LOG_EMERGENCY, "Failed to init protocol", __FILE__, __LINE__); return -1; } return 0; }
int main(int argc, char *argv[]) { loginit(NULL); if (argc < 4) fatal("Expected 3 arguments"); parseargs(argc, argv); rng(&r); int w = strtol(argv[1], NULL, 10); int h = strtol(argv[2], NULL, 10); int d = strtol(argv[3], NULL, 10); Lvl *lvl = lvlnew(d, w, h, 0); unsigned int x0 = 2, y0 = 2; if (randstart) { x0 = rnd(1, w-2); y0 = rnd(1, h-2); } mvsinit(); do{ init(lvl); if (addwater) water(lvl); Loc loc = (Loc) { x0, y0, 0 }; Path *p = pathnew(lvl); pathbuild(lvl, p, loc); pathfree(p); morereach(lvl); closeunits(lvl); }while(closeunreach(lvl) < lvl->w * lvl->h * lvl->d * 0.40); stairs(&r, lvl, x0, y0); bool foundstart = false; for (int x = 0; x < w; x++) { for (int y = 0; y < h; y++) { if (blk(lvl, x, y, 0)->tile == 'u' || blk(lvl, x, y, 0)->tile == 'U') { foundstart = true; break; } } } assert(foundstart); lvlwrite(stdout, lvl); lvlfree(lvl); return 0; }
int main(int argc, char *argv[]) { int *ids; loginit(NULL); Rng r; int usdargs = rng(&r, argc, argv); argc -= usdargs; argv += usdargs; int n = idargs(argc, argv, &ids); if (argc < 3) fatal("usage: enmgen [-s <seed>] <ID>+ <num>"); long num = strtol(argv[argc-1], NULL, 10); if (num == LLONG_MIN || num == LLONG_MAX) fatal("Invalid number: %s", argv[argc-1]); Zone *zn = zoneread(stdin); if (!zn) die("Failed to read the zone: %s", miderrstr()); Loc ls[zn->lvl->d * zn->lvl->w * zn->lvl->h]; int nls = locs(zn, ls); int i; for (i = 0; i < num && nls > 0; i++) { int idind = rngintincl(&r, 0, n); int lind = rngintincl(&r, 0, nls); Loc l = ls[lind]; if (nls > 1) ls[lind] = ls[nls-1]; nls--; Enemy enm; if (!enemyinit(&enm, ids[idind], l.p.x, l.p.y)) fatal("Failed to initialize enemy with ID: %d", ids[idind]); if (!zoneaddenemy(zn, l.z, enm)) { nls = rmz(ls, nls, l.z); num--; } } if (i < num) fatal("Failed to place all items"); zonewrite(stdout, zn); zonefree(zn); xfree(ids); return 0; }
bool LogWriter::write(char *pbuffer, int len) { if(0 != access(m_filelocation, W_OK)) { pthread_mutex_lock(&m_mutex); if(0 != access(m_filelocation, W_OK)) { logclose(); loginit(m_system_level, m_filelocation, m_isappend, m_issync); } pthread_mutex_unlock(&m_mutex); } if(1 == fwrite(pbuffer, len, 1, fp)) { if(m_issync) fflush(fp); *pbuffer='\0'; } else { int x = errno; fprintf(stderr, "Failed to write to logfile. errno:%s message:%s", strerror(x), pbuffer); return false; } return true; }
bool LogWriter::log(ELogLevel l, const char* format, ...) { if (l > level_) { return false; } char* bPtr; va_list ap; va_start(ap, format); int blen = ::vasprintf(&bPtr, format, ap); if (blen < 0) { va_end(ap); return false; } va_end(ap); char header[100] = { 0 }; int hlen = 0; logHeader(header, hlen, l); INIT_IOV(2); SET_IOV_LEN(header, hlen); SET_IOV_LEN(bPtr, blen); if (inode_ != fileNode() || !inode_) { rwlock_.WLock(); if (inode_ != fileNode() || !inode_) { logclose(); loginit(level_, logFile_); } rwlock_.UnLock(); } bool ret = true; rwlock_.RLock(); if (::writev(fd_, iovs, 2) <= 0) { ret = false; } rwlock_.UnLock(); free(bPtr); return ret; }
int main(int argc, char **argv) { int ch, i, fd, utc, r, verbose, debug, csv; extern char *optarg; extern int optind; struct store_flow_complete flow; struct store_v2_flow_complete flow_v2; char buf[2048], ebuf[512]; const char *ffile, *ofile; FILE *ffilef; int ofd, read_legacy, head, nflows; u_int32_t disp_mask; struct flowd_config filter_config; struct store_v2_header hdr_v2; utc = verbose = debug = read_legacy = csv = 0; ofile = ffile = NULL; ofd = -1; ffilef = NULL; head = 0; bzero(&filter_config, sizeof(filter_config)); while ((ch = getopt(argc, argv, "H:LUdf:ho:qvc")) != -1) { switch (ch) { case 'h': usage(); return (0); case 'H': if ((head = atoi(optarg)) <= 0) { fprintf(stderr, "Invalid -H value.\n"); usage(); exit(1); } break; case 'L': read_legacy = 1; break; case 'U': utc = 1; break; case 'd': debug = 1; filter_config.opts |= FLOWD_OPT_VERBOSE; break; case 'f': ffile = optarg; break; case 'o': ofile = optarg; break; case 'q': verbose = -1; break; case 'v': verbose = 1; break; case 'c': csv = 1; break; default: usage(); exit(1); } } loginit(PROGNAME, 1, debug); if (argc - optind < 1) { fprintf(stderr, "No logfile specified\n"); usage(); exit(1); } if (ffile != NULL) { if ((ffilef = fopen(ffile, "r")) == NULL) logerr("fopen(%s)", ffile); if (parse_config(ffile, ffilef, &filter_config, 1) != 0) exit(1); fclose(ffilef); } if (ofile != NULL) { if (strcmp(ofile, "-") == 0) { if (!debug) verbose = -1; ofile = NULL; if (isatty(STDOUT_FILENO)) logerrx("Refusing to write binary flow data to " "standard output."); } ofd = open_start_log(ofile, debug); } if (filter_config.store_mask == 0) filter_config.store_mask = STORE_FIELD_ALL; disp_mask = (verbose > 0) ? STORE_DISPLAY_ALL: STORE_DISPLAY_BRIEF; disp_mask &= filter_config.store_mask; for (i = optind; i < argc; i++) { if (strcmp(argv[i], "-") == 0) fd = STDIN_FILENO; else if ((fd = open(argv[i], O_RDONLY)) == -1) logerr("open(%s)", argv[i]); if (read_legacy && store_v2_get_header(fd, &hdr_v2, ebuf, sizeof(ebuf)) != STORE_ERR_OK) logerrx("%s", ebuf); if (verbose >= 1) { printf("LOGFILE %s", argv[i]); if (read_legacy) printf(" started at %s", iso_time(ntohl(hdr_v2.start_time), utc)); printf("\n"); fflush(stdout); } if (csv == 1) { csv++; printf("#:unix_secs,unix_nsecs,sysuptime,exaddr," "dpkts,doctets,first,last,engine_type,engine_id," "srcaddr,dstaddr,nexthop,input,output,srcport," "dstport,prot,tos,tcp_flags,src_mask,dst_mask," "src_as,dst_as\n"); } for (nflows = 0; head == 0 || nflows < head; nflows++) { bzero(&flow, sizeof(flow)); if (read_legacy) r = store_v2_get_flow(fd, &flow_v2, ebuf, sizeof(ebuf)); else r = store_get_flow(fd, &flow, ebuf, sizeof(ebuf)); if (r == STORE_ERR_EOF) break; else if (r != STORE_ERR_OK) logerrx("%s", ebuf); if (read_legacy && store_v2_flow_convert(&flow_v2, &flow) == -1) logerrx("legacy flow conversion failed"); if (ffile != NULL && filter_flow(&flow, &filter_config.filter_list) == FF_ACTION_DISCARD) continue; if (csv) { store_format_flow_flowtools_csv(&flow, buf, sizeof(buf), utc, disp_mask, 0); printf("%s\n", buf); } else if (verbose >= 0) { store_format_flow(&flow, buf, sizeof(buf), utc, disp_mask, 0); printf("%s\n", buf); fflush(stdout); } if (ofd != -1 && store_put_flow(ofd, &flow, filter_config.store_mask, ebuf, sizeof(ebuf)) == -1) logerrx("%s", ebuf); } if (fd != STDIN_FILENO) close(fd); } if (ofd != -1) close(ofd); if (ffile != NULL && debug) dump_config(&filter_config, "final", 1); return (0); }
int main(int argc, char *argv[]) { char *system = NOSTR; int i; char *p; char sbuf[15]; gid = getgid(); egid = getegid(); uid = getuid(); euid = geteuid(); if (equal(sname(argv[0]), "cu")) { cumode = 1; cumain(argc, argv); goto cucommon; } if (argc > 4) { (void) fprintf(stderr, "usage: tip [-v] [-speed] [system-name]\n"); return (1); } if (!isatty(0)) { (void) fprintf(stderr, "tip: must be interactive\n"); return (1); } for (; argc > 1; argv++, argc--) { if (argv[1][0] != '-') system = argv[1]; else switch (argv[1][1]) { case 'v': vflag++; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': BR = atoi(&argv[1][1]); break; default: (void) fprintf(stderr, "tip: %s, unknown option\n", argv[1]); break; } } (void) setlocale(LC_CTYPE, ""); if (system == NOSTR) goto notnumber; for (p = system; *p; p++) if (isalpha(*p)) goto notnumber; /* * System name is really a phone number... * Copy the number then stomp on the original (in case the number * is private, we don't want 'ps' or 'w' to find it). */ if (strlen(system) > sizeof (PNbuf) - 1) { (void) fprintf(stderr, "tip: phone number too long (max = %d bytes)\n", sizeof (PNbuf) - 1); return (1); } (void) strncpy(PNbuf, system, sizeof (PNbuf) - 1); for (p = system; *p; p++) *p = '\0'; PN = PNbuf; (void) snprintf(sbuf, sizeof (sbuf), "tip%d", BR); system = sbuf; notnumber: (void) signal(SIGINT, (sig_handler_t)cleanup); (void) signal(SIGQUIT, (sig_handler_t)cleanup); (void) signal(SIGHUP, (sig_handler_t)cleanup); (void) signal(SIGTERM, (sig_handler_t)cleanup); if ((i = hunt(system)) == 0) { (void) printf("all ports busy\n"); return (3); } if (i == -1) { (void) printf("link down\n"); delock(uucplock); return (3); } setbuf(stdout, NULL); loginit(); /* * Now that we have the logfile and the ACU open * return to the real uid and gid. These things will * be closed on exit. The saved-setuid uid and gid * allows us to get the original setuid permissions back * for removing the uucp lock. */ userperm(); /* * Kludge, there's no easy way to get the initialization * in the right order, so force it here. * Do the open here, before we change back to real uid. * We will check whether the open succeeded later, when * (and if) we actually go to use the file. */ if ((PH = getenv("PHONES")) == NOSTR) { myperm(); PH = "/etc/phones"; } phfd = fopen(PH, "r"); userperm(); vinit(); /* init variables */ setparity("none"); /* set the parity table */ if ((i = speed(number(value(BAUDRATE)))) == NULL) { (void) printf("tip: bad baud rate %d\n", number(value(BAUDRATE))); myperm(); delock(uucplock); return (3); } /* * Hardwired connections require the * line speed set before they make any transmissions * (this is particularly true of things like a DF03-AC) */ if (HW) ttysetup(i); if (p = connect()) { (void) printf("\07%s\n[EOT]\n", p); myperm(); delock(uucplock); return (1); } /* * Always setup the tty again here in case hardware flow * control was selected, which can only be set after the * connection is made, or in case this is not a hardwired * modem (rare these days) that likewise can only be setup * after the connection is made. */ ttysetup(i); cucommon: /* * From here down the code is shared with * the "cu" version of tip. */ (void) ioctl(0, TCGETS, (char *)&defarg); arg = defarg; /* turn off input processing */ arg.c_lflag &= ~(ICANON|ISIG|ECHO|IEXTEN); arg.c_cc[VMIN] = 1; arg.c_cc[VTIME] = 0; arg.c_iflag &= ~(INPCK|IXON|IXOFF|ICRNL); arg.c_oflag = 0; /* turn off all output processing */ /* handle tandem mode in case was set in remote file */ if (boolean(value(TAND))) tandem("on"); else tandem("off"); raw(); (void) pipe(fildes); (void) pipe(repdes); (void) signal(SIGALRM, (sig_handler_t)timeout); /* * Everything's set up now: * connection established (hardwired or dialup) * line conditioned (baud rate, mode, etc.) * internal data structures (variables) * so, fork one process for local side and one for remote. */ if (CM != NOSTR) { (void) sleep(2); /* let line settle */ parwrite(FD, (unsigned char *)CM, strlen(CM)); } (void) printf(cumode ? "Connected\r\n" : "\07connected\r\n"); (void) signal(SIGCHLD, (sig_handler_t)deadkid); if (pid = fork()) tipin(); else tipout(); /*NOTREACHED*/ }
int main(int argc, char **argv) { address_tuple_t tuple; char *progname; char *server = NULL; char *port = NULL; char *myeid = NULL; char *pidfile = NULL; char *vnodeid = NULL; char buf[BUFSIZ], ipaddr[32]; char hostname[MAXHOSTNAMELEN]; struct hostent *he; int c; struct in_addr myip; FILE *fp; progname = argv[0]; while ((c = getopt(argc, argv, "ds:p:e:i:v:")) != -1) { switch (c) { case 'd': debug++; break; case 's': server = optarg; break; case 'p': port = optarg; break; case 'i': pidfile = optarg; break; case 'e': myeid = optarg; break; case 'v': vnodeid = optarg; break; default: usage(progname); } } argc -= optind; argv += optind; if (argc) usage(progname); if (! myeid) fatal("Must provide pid/eid"); if (debug) loginit(0, 0); else { loginit(1, "evproxy"); /* See below for daemonization */ } /* * Get our IP address. Thats how we name this host to the * event System. */ if (gethostname(hostname, MAXHOSTNAMELEN) == -1) { fatal("could not get hostname: %s\n", strerror(errno)); } if (! (he = gethostbyname(hostname))) { fatal("could not get IP address from hostname: %s", hostname); } memcpy((char *)&myip, he->h_addr, he->h_length); strcpy(ipaddr, inet_ntoa(myip)); /* * If server is not specified, then it defaults to EVENTSERVER. * This allows the client to work on either users.emulab.net * or on a client node. */ if (!server) server = "event-server"; /* * XXX Need to daemonize earlier or the threads go away. */ if (!debug) daemon(0, 0); /* * Convert server/port to elvin thing. * * XXX This elvin string stuff should be moved down a layer. */ snprintf(buf, sizeof(buf), "elvin://%s%s%s", server, (port ? ":" : ""), (port ? port : "")); server = buf; /* * Construct an address tuple for generating the event. */ tuple = address_tuple_alloc(); if (tuple == NULL) { fatal("could not allocate an address tuple"); } /* Register with the event system on boss */ bosshandle = event_register(server, 1); if (bosshandle == NULL) { fatal("could not register with remote event system"); } /* Register with the event system on the local node */ localhandle = event_register("elvin://localhost", 1); if (localhandle == NULL) { fatal("could not register with local event system"); } /* * Create a subscription to pass to the remote server. We want * all events for this node, or all events for the experiment * if the node is unspecified (we want to avoid getting events * that are directed at specific nodes that are not us!). */ sprintf(buf, "%s,%s", ADDRESSTUPLE_ALL, ipaddr); tuple->host = buf; tuple->expt = myeid; /* Subscribe to the test event: */ if (! event_subscribe(bosshandle, callback, tuple, "event received")) { fatal("could not subscribe to events on remote server"); } tuple->host = ADDRESSTUPLE_ALL; tuple->scheduler = 1; if (! event_subscribe(localhandle, sched_callback, tuple, NULL)) { fatal("could not subscribe to events on remote server"); } signal(SIGTERM, sigterm); /* * Stash the pid away. */ if (! pidfile) { sprintf(buf, "%s/evproxy.pid", _PATH_VARRUN); pidfile = buf; } fp = fopen(pidfile, "w"); if (fp != NULL) { fprintf(fp, "%d\n", getpid()); (void) fclose(fp); } /* Begin the event loop, waiting to receive event notifications */ while (! stop) { struct timeval tv = { 5, 0 }; select(0, NULL, NULL, NULL, &tv); } unlink(pidfile); /* Unregister with the remote event system: */ if (event_unregister(bosshandle) == 0) { fatal("could not unregister with remote event system"); } /* Unregister with the local event system: */ if (event_unregister(localhandle) == 0) { fatal("could not unregister with local event system"); } return 0; }
/* Initialize networking. * Bind to ip and port. * ip must be in network order EX: 127.0.0.1 = (7F000001). * port is in host byte order (this means don't worry about it). * * return Networking_Core object if no problems * return NULL if there are problems. */ Networking_Core *new_networking(IP ip, uint16_t port) { #ifdef TOX_ENABLE_IPV6 /* maybe check for invalid IPs like 224+.x.y.z? if there is any IP set ever */ if (ip.family != AF_INET && ip.family != AF_INET6) { #ifdef DEBUG fprintf(stderr, "Invalid address family: %u\n", ip.family); #endif return NULL; } #endif if (at_startup() != 0) return NULL; Networking_Core *temp = calloc(1, sizeof(Networking_Core)); if (temp == NULL) return NULL; #ifdef TOX_ENABLE_IPV6 temp->family = ip.family; #else temp->family = AF_INET; #endif temp->port = 0; /* Initialize our socket. */ /* add log message what we're creating */ temp->sock = socket(temp->family, SOCK_DGRAM, IPPROTO_UDP); /* Check for socket error. */ #ifdef WIN32 if (temp->sock == INVALID_SOCKET) { /* MSDN recommends this. */ free(temp); return NULL; } #else if (temp->sock < 0) { #ifdef DEBUG fprintf(stderr, "Failed to get a socket?! %u, %s\n", errno, strerror(errno)); #endif free(temp); return NULL; } #endif /* Functions to increase the size of the send and receive UDP buffers. */ int n = 1024 * 1024 * 2; setsockopt(temp->sock, SOL_SOCKET, SO_RCVBUF, (char *)&n, sizeof(n)); setsockopt(temp->sock, SOL_SOCKET, SO_SNDBUF, (char *)&n, sizeof(n)); /* Enable broadcast on socket */ int broadcast = 1; setsockopt(temp->sock, SOL_SOCKET, SO_BROADCAST, (char *)&broadcast, sizeof(broadcast)); /* Set socket nonblocking. */ #ifdef WIN32 /* I think this works for Windows. */ u_long mode = 1; /* ioctl(sock, FIONBIO, &mode); */ ioctlsocket(temp->sock, FIONBIO, &mode); #else fcntl(temp->sock, F_SETFL, O_NONBLOCK, 1); #endif /* Bind our socket to port PORT and the given IP address (usually 0.0.0.0 or ::) */ uint16_t *portptr = NULL; struct sockaddr_storage addr; size_t addrsize; #ifdef TOX_ENABLE_IPV6 if (temp->family == AF_INET) { IP4 ip4 = ip.ip4; #else IP4 ip4 = ip; #endif addrsize = sizeof(struct sockaddr_in); struct sockaddr_in *addr4 = (struct sockaddr_in *)&addr; addr4->sin_family = AF_INET; addr4->sin_port = 0; addr4->sin_addr = ip4.in_addr; portptr = &addr4->sin_port; #ifdef TOX_ENABLE_IPV6 } else if (temp->family == AF_INET6) { addrsize = sizeof(struct sockaddr_in6); struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&addr; addr6->sin6_family = AF_INET6; addr6->sin6_port = 0; addr6->sin6_addr = ip.ip6.in6_addr; addr6->sin6_flowinfo = 0; addr6->sin6_scope_id = 0; portptr = &addr6->sin6_port; } else return NULL; if (ip.family == AF_INET6) { char ipv6only = 0; #ifdef LOGGING errno = 0; int res = #endif setsockopt(temp->sock, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&ipv6only, sizeof(ipv6only)); #ifdef LOGGING if (res < 0) { sprintf(logbuffer, "Failed to enable dual-stack on IPv6 socket, won't be able to receive from/send to IPv4 addresses. (%u, %s)\n", errno, strerror(errno)); loglog(logbuffer); } else loglog("Embedded IPv4 addresses enabled successfully.\n"); #endif /* multicast local nodes */ struct ipv6_mreq mreq; memset(&mreq, 0, sizeof(mreq)); mreq.ipv6mr_multiaddr.s6_addr[ 0] = 0xFF; mreq.ipv6mr_multiaddr.s6_addr[ 1] = 0x02; mreq.ipv6mr_multiaddr.s6_addr[15] = 0x01; mreq.ipv6mr_interface = 0; #ifdef LOGGING errno = 0; res = #endif setsockopt(temp->sock, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, (char *)&mreq, sizeof(mreq)); #ifdef LOGGING if (res < 0) { sprintf(logbuffer, "Failed to activate local multicast membership. (%u, %s)\n", errno, strerror(errno)); loglog(logbuffer); } else loglog("Local multicast group FF02::1 joined successfully.\n"); #endif } #endif /* a hanging program or a different user might block the standard port; * as long as it isn't a parameter coming from the commandline, * try a few ports after it, to see if we can find a "free" one * * if we go on without binding, the first sendto() automatically binds to * a free port chosen by the system (i.e. anything from 1024 to 65535) * * returning NULL after bind fails has both advantages and disadvantages: * advantage: * we can rely on getting the port in the range 33445..33450, which * enables us to tell joe user to open their firewall to a small range * * disadvantage: * some clients might not test return of tox_new(), blindly assuming that * it worked ok (which it did previously without a successful bind) */ uint16_t port_to_try = port; *portptr = htons(port_to_try); int tries, res; for (tries = TOX_PORTRANGE_FROM; tries <= TOX_PORTRANGE_TO; tries++) { res = bind(temp->sock, (struct sockaddr *)&addr, addrsize); if (!res) { temp->port = *portptr; #ifdef LOGGING loginit(temp->port); sprintf(logbuffer, "Bound successfully to %s:%u.\n", ip_ntoa(&ip), ntohs(temp->port)); loglog(logbuffer); #endif /* errno isn't reset on success, only set on failure, the failed * binds with parallel clients yield a -EPERM to the outside if * errno isn't cleared here */ if (tries > 0) errno = 0; return temp; } port_to_try++; if (port_to_try > TOX_PORTRANGE_TO) port_to_try = TOX_PORTRANGE_FROM; *portptr = htons(port_to_try); } #ifdef DEBUG fprintf(stderr, "Failed to bind socket: %u, %s (IP/Port: %s:%u\n", errno, strerror(errno), ip_ntoa(&ip), port); #endif kill_networking(temp); return NULL; }
int main(int argc, char *argv[]) { char *system = NULL; int i; char *p; char sbuf[12]; gid = getgid(); egid = getegid(); uid = getuid(); euid = geteuid(); #if INCLUDE_CU_INTERFACE if (equal(sname(argv[0]), "cu")) { cumode = 1; cumain(argc, argv); goto cucommon; } #endif /* INCLUDE_CU_INTERFACE */ if (argc > 4) usage(); if (!isatty(0)) errx(1, "must be interactive"); for (; argc > 1; argv++, argc--) { if (argv[1][0] != '-') system = argv[1]; else switch (argv[1][1]) { case 'v': vflag++; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': BR = atoi(&argv[1][1]); break; default: warnx("%s, unknown option", argv[1]); break; } } if (system == NULL) goto notnumber; if (isalpha(*system)) goto notnumber; /* * System name is really a phone number... * Copy the number then stomp on the original (in case the number * is private, we don't want 'ps' or 'w' to find it). */ if (strlen(system) > sizeof(PNbuf) - 1) errx(1, "phone number too long (max = %zd bytes)", sizeof PNbuf - 1); strncpy(PNbuf, system, sizeof(PNbuf) - 1); for (p = system; *p; p++) *p = '\0'; PN = PNbuf; (void)snprintf(sbuf, sizeof(sbuf), "tip%ld", BR); system = sbuf; notnumber: (void)signal(SIGINT, cleanup); (void)signal(SIGQUIT, cleanup); (void)signal(SIGHUP, cleanup); (void)signal(SIGTERM, cleanup); (void)signal(SIGUSR1, tipdone); if ((i = hunt(system)) == 0) { printf("all ports busy\n"); exit(3); } if (i == -1) { printf("link down\n"); (void)uu_unlock(uucplock); exit(3); } setbuf(stdout, NULL); loginit(); /* * Kludge, their's no easy way to get the initialization * in the right order, so force it here */ if ((PH = getenv("PHONES")) == NULL) PH = _PATH_PHONES; vinit(); /* init variables */ setparity("even"); /* set the parity table */ if ((i = speed(number(value(BAUDRATE)))) == 0) { printf("tip: bad baud rate %d\n", number(value(BAUDRATE))); (void)uu_unlock(uucplock); exit(3); } /* * Now that we have the logfile and the ACU open * return to the real uid and gid. These things will * be closed on exit. Swap real and effective uid's * so we can get the original permissions back * for removing the uucp lock. */ user_uid(); /* * Hardwired connections require the * line speed set before they make any transmissions * (this is particularly true of things like a DF03-AC) */ if (HW) ttysetup(i); if ((p = connect())) { printf("\07%s\n[EOT]\n", p); daemon_uid(); (void)uu_unlock(uucplock); exit(1); } if (!HW) ttysetup(i); cucommon: /* * From here down the code is shared with * the "cu" version of tip. */ #if HAVE_TERMIOS tcgetattr (0, &otermios); ctermios = otermios; #ifndef _POSIX_SOURCE ctermios.c_iflag = (IMAXBEL|IXANY|ISTRIP|IXON|BRKINT); ctermios.c_lflag = (PENDIN|IEXTEN|ISIG|ECHOCTL|ECHOE|ECHOKE); #else ctermios.c_iflag = (ISTRIP|IXON|BRKINT); ctermios.c_lflag = (PENDIN|IEXTEN|ISIG|ECHOE); #endif ctermios.c_cflag = (CLOCAL|HUPCL|CREAD|CS8); ctermios.c_cc[VINTR] = ctermios.c_cc[VQUIT] = -1; ctermios.c_cc[VSUSP] = ctermios.c_cc[VDSUSP] = ctermios.c_cc[VDISCARD] = ctermios.c_cc[VLNEXT] = -1; #else /* HAVE_TERMIOS */ ioctl(0, TIOCGETP, (char *)&defarg); ioctl(0, TIOCGETC, (char *)&defchars); ioctl(0, TIOCGLTC, (char *)&deflchars); ioctl(0, TIOCGETD, (char *)&odisc); arg = defarg; arg.sg_flags = ANYP | CBREAK; tchars = defchars; tchars.t_intrc = tchars.t_quitc = -1; ltchars = deflchars; ltchars.t_suspc = ltchars.t_dsuspc = ltchars.t_flushc = ltchars.t_lnextc = -1; #endif /* HAVE_TERMIOS */ raw(); pipe(fildes); pipe(repdes); (void)signal(SIGALRM, timeoutfunc); /* * Everything's set up now: * connection established (hardwired or dialup) * line conditioned (baud rate, mode, etc.) * internal data structures (variables) * so, fork one process for local side and one for remote. */ printf(cumode ? "Connected\r\n" : "\07connected\r\n"); if (LI != NULL && tiplink (LI, 0) != 0) { tipabort ("login failed"); } if ((pid = fork())) tipin(); else tipout(); /*NOTREACHED*/ }
/* * Botch the interface to look like cu's */ void cumain(int argc, char *argv[]) { int i; static char sbuf[12]; if (argc < 2) { printf("usage: cu telno [-t] [-s speed] [-a acu] [-l line] [-#]\n"); exit(8); } CU = DV = NULL; BR = DEFBR; for (; argc > 1; argv++, argc--) { if (argv[1][0] != '-') PN = argv[1]; else switch (argv[1][1]) { case 't': HW = 1, DU = -1; --argc; continue; case 'a': CU = argv[2]; ++argv; --argc; break; case 's': if (argc < 3 || speed(atoi(argv[2])) == 0) { fprintf(stderr, "cu: unsupported speed %s\n", argv[2]); exit(3); } BR = atoi(argv[2]); ++argv; --argc; break; case 'l': DV = argv[2]; ++argv; --argc; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (CU) CU[strlen(CU)-1] = argv[1][1]; if (DV) DV[strlen(DV)-1] = argv[1][1]; break; default: printf("Bad flag %s", argv[1]); break; } } signal(SIGINT, cleanup); signal(SIGQUIT, cleanup); signal(SIGHUP, cleanup); signal(SIGTERM, cleanup); /* * The "cu" host name is used to define the * attributes of the generic dialer. */ (void)snprintf(sbuf, sizeof(sbuf), "cu%ld", BR); if ((i = hunt(sbuf)) == 0) { printf("all ports busy\n"); exit(3); } if (i == -1) { printf("link down\n"); (void)uu_unlock(uucplock); exit(3); } setbuf(stdout, NULL); loginit(); user_uid(); vinit(); setparity("none"); boolean(value(VERBOSE)) = 0; if (HW) ttysetup(speed(BR)); if (connect()) { printf("Connect failed\n"); daemon_uid(); (void)uu_unlock(uucplock); exit(1); } if (!HW) ttysetup(speed(BR)); exit(0); }
int main(int argc, char** argv) { if (argc < 2) { fprintf(stderr, "use: --exec your_process start --log your_log_file {default[/var/log/bumo-daemon.log]} \n"); exit(EXIT_FAILURE); } std::string skey = ""; std::map<std::string, std::string> commands; for (int i = 1; i < argc;i++) { std::string cmd(argv[i]); if (cmd.find("--") != std::string::npos) { skey = cmd; } else { if (commands[skey].empty()) commands[skey] = cmd; else commands[skey] = commands[skey] + std::string(" ") + cmd; } } std::string str_exec; std::string str_log; if (commands.find("--exec") == commands.end()) { fprintf(stderr, "use: --exec your_process start --log your_log_file {default[/var/log/bumo-daemon.log]} \n"); exit(EXIT_FAILURE); } str_exec = commands["--exec"]; if (commands.find("--log") == commands.end()) { str_log = "/var/log/bumo-daemon.log"; } else { str_log = commands["--log"]; } if (!loginit(str_log.c_str())) { fprintf(stderr, "open log file (%s) fail", str_log.c_str()); exit(EXIT_FAILURE); } LOG("the command is : [%s]", str_exec.c_str()); do { int fd; pthread_mutex_t *mptr = NULL; pthread_mutexattr_t mattr; fd = open("/dev/zero", O_RDWR, 0); mptr = (pthread_mutex_t*)mmap(0, sizeof(pthread_mutex_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); close(fd); pthread_mutexattr_init(&mattr); pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(mptr, &mattr); void *shm = NULL;//分配的共享内存的原始首地址 int64_t *shared;//指向shm int shmid;//共享内存标识符 //创建共享内存 shmid = shmget((key_t)1234, sizeof(int64_t), 0666 | IPC_CREAT); if (shmid == -1) { LOG("shmget failed"); break; } //将共享内存连接到当前进程的地址空间 shm = shmat(shmid, 0, 0); if (shm == (void*)-1) { break; } shared = (int64_t*)shm; int64_t last = 0; g_enable_ = true; InstallSignal(); while (g_enable_)//读取共享内存中的数据 { sleep(100); pthread_mutex_lock(mptr); LOG("last:%ld now:%ld ", last, *shared); if (last == *shared) { LOG("something wrong with process... do (%s)", str_exec.c_str()); system(str_exec.c_str()); } last = *shared; pthread_mutex_unlock(mptr); } //把共享内存从当前进程中分离 if (shmdt(shm) == -1) { LOG("shmdt failed"); break; } //删除共享内存 if (shmctl(shmid, IPC_RMID, 0) == -1) { LOG("shmctl(IPC_RMID) failed"); break; } log_close(); } while (false); log_close(); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { fprintf(stderr,"Proxy Start yuruiz\n"); int http_port; char *log_file; int http_listen_socket, http_client_sock; struct sockaddr_in http_addr, cli_addr; socklen_t conn_size; pool conn_pool; if (argc < 7 || argc > 8) { printf(USAGE, argv[0]); return EXIT_FAILURE; } log_file = argv[1]; alpha = atof(argv[2]); http_port = atoi(argv[3]); fake_ip = argv[4]; proxy.dns_ip = argv[5]; proxy.dns_port = argv[6]; if (argc == 8) { www_ip = argv[7]; } loginit(log_file); fprintf(stderr,"-------------------Server Start------------------\n"); if ((http_listen_socket = open_port(http_port, &http_addr)) == -1) { fprintf(stderr,"Open port failed\n"); return EXIT_FAILURE; } // parse fake-ip bzero(&proxy.myaddr, sizeof(struct sockaddr_in)); proxy.myaddr.sin_family = AF_INET; inet_aton(fake_ip, &proxy.myaddr.sin_addr); proxy.myaddr.sin_port = htons(0); init_pool(http_listen_socket, &conn_pool); do { // printf("Pool start\n"); conn_pool.ready_set = conn_pool.read_set; conn_pool.nconn = select(conn_pool.maxfd + 1, &conn_pool.ready_set, NULL, NULL, NULL); conn_size = sizeof(cli_addr); if (FD_ISSET(http_listen_socket, &conn_pool.ready_set)) { fprintf(stderr,"Adding new http connection\n"); if ((http_client_sock = accept(http_listen_socket, (struct sockaddr *) &cli_addr, &conn_size)) == -1) { fprintf(stderr,"Error accepting http connection.\n"); continue; } add_conn(http_client_sock, &conn_pool, &cli_addr); } conn_handle(&conn_pool); } while (1); close_socket(http_listen_socket); return EXIT_SUCCESS; }
int main(int argc, char **argv) { int sock, err, c; int reboot = 0, restart = 0, query = 0; struct sockaddr_in name, target; boot_info_t boot_info; boot_what_t *boot_whatp = (boot_what_t *) &boot_info.data; extern char build_info[]; struct hostent *he; progname = argv[0]; while ((c = getopt(argc, argv, "dhvrRq")) != -1) { switch (c) { case 'd': debug++; break; case 'r': reboot++; break; case 'R': restart++; break; case 'q': query++; break; case 'v': fprintf(stderr, "%s\n", build_info); exit(0); break; case 'h': case '?': default: usage(); } } argc -= optind; argv += optind; if (!argc) usage(); if (query && (reboot || restart)) usage(); if (debug) loginit(0, 0); else loginit(1, "bootinfo"); if (debug) info("%s\n", build_info); /* Make sure we can map target. */ if ((he = gethostbyname(argv[0])) == NULL) { errorc("gethostbyname(%s)", argv[0]); exit(1); } bzero(&target, sizeof(target)); memcpy((char *)&target.sin_addr, he->h_addr, he->h_length); target.sin_family = AF_INET; target.sin_port = htons((u_short) BOOTWHAT_SRCPORT); err = open_bootinfo_db(); if (err) { error("could not open database"); exit(1); } #ifdef EVENTSYS err = bievent_init(); if (err) { error("could not initialize event system"); exit(1); } #endif /* Create socket */ sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) { errorc("opening datagram socket"); exit(1); } err = 1; if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, (char *)&err, sizeof(err)) < 0) errorc("setsockopt(SO_REUSEADDR)"); /* Create name. */ name.sin_family = AF_INET; name.sin_addr.s_addr = INADDR_ANY; name.sin_port = htons((u_short) BOOTWHAT_SENDPORT); if (bind(sock, (struct sockaddr *) &name, sizeof(name))) { errorc("binding datagram socket"); exit(1); } bzero(&boot_info, sizeof(boot_info)); boot_info.version = BIVERSION_CURRENT; if (reboot || restart) { boot_whatp->type = reboot ? BIBOOTWHAT_TYPE_REBOOT : BIBOOTWHAT_TYPE_RESTART; #ifdef EVENTSYS bievent_send(target.sin_addr, (void *) NULL, TBDB_NODESTATE_SHUTDOWN); #endif } else if (query) { boot_whatp->type = BIBOOTWHAT_TYPE_AUTO; #ifdef EVENTSYS bievent_send(target.sin_addr, (void *) NULL, TBDB_NODESTATE_PXEWAKEUP); #endif } else { err = query_bootinfo_db(target.sin_addr, NULL, boot_info.version, boot_whatp, NULL); if (err) { fatal("Could not send bootinfo packet!"); } #ifdef EVENTSYS bievent_send(target.sin_addr, (void *) NULL, TBDB_NODESTATE_PXEBOOTING); switch (boot_whatp->type) { case BIBOOTWHAT_TYPE_PART: case BIBOOTWHAT_TYPE_SYSID: case BIBOOTWHAT_TYPE_MB: case BIBOOTWHAT_TYPE_MFS: bievent_send(target.sin_addr, (void *) NULL, TBDB_NODESTATE_BOOTING); break; case BIBOOTWHAT_TYPE_WAIT: bievent_send(target.sin_addr, (void *) NULL, TBDB_NODESTATE_PXEWAIT); break; default: error("%s: invalid boot directive: %d\n", inet_ntoa(target.sin_addr), boot_whatp->type); break; } #endif } log_bootwhat(target.sin_addr, boot_whatp); boot_info.status = BISTAT_SUCCESS; boot_info.opcode = BIOPCODE_BOOTWHAT_ORDER; #ifdef ELABINELAB /* This is too brutal to even describe */ elabinelab_hackcheck(&target); #endif if (sendto(sock, (char *)&boot_info, sizeof(boot_info), 0, (struct sockaddr *)&target, sizeof(target)) < 0) errorc("sendto"); close(sock); close_bootinfo_db(); #ifdef EVENTSYS bievent_shutdown(); #endif exit(0); }
int main(int argc, char *argv[]) { char *sys = NOSTR, sbuf[12], *p; int i; /* XXX preserve previous braindamaged behavior */ setboolean(value(DC), TRUE); gid = getgid(); egid = getegid(); uid = getuid(); euid = geteuid(); if (equal(__progname, "cu")) { cumode = 1; cumain(argc, argv); goto cucommon; } if (argc > 4) { fprintf(stderr, "usage: tip [-v] [-speed] [system-name]\n"); exit(1); } if (!isatty(0)) { fprintf(stderr, "%s: must be interactive\n", __progname); exit(1); } for (; argc > 1; argv++, argc--) { if (argv[1][0] != '-') sys = argv[1]; else switch (argv[1][1]) { case 'v': vflag++; break; case 'n': noesc++; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': BR = atoi(&argv[1][1]); break; default: fprintf(stderr, "%s: %s, unknown option\n", __progname, argv[1]); break; } } if (sys == NOSTR) goto notnumber; if (isalpha(*sys)) goto notnumber; /* * System name is really a phone number... * Copy the number then stomp on the original (in case the number * is private, we don't want 'ps' or 'w' to find it). */ if (strlen(sys) > sizeof PNbuf - 1) { fprintf(stderr, "%s: phone number too long (max = %d bytes)\n", __progname, (int)sizeof(PNbuf) - 1); exit(1); } strlcpy(PNbuf, sys, sizeof PNbuf - 1); for (p = sys; *p; p++) *p = '\0'; PN = PNbuf; (void)snprintf(sbuf, sizeof(sbuf), "tip%ld", BR); sys = sbuf; notnumber: (void)signal(SIGINT, cleanup); (void)signal(SIGQUIT, cleanup); (void)signal(SIGHUP, cleanup); (void)signal(SIGTERM, cleanup); (void)signal(SIGCHLD, SIG_DFL); if ((i = hunt(sys)) == 0) { printf("all ports busy\n"); exit(3); } if (i == -1) { printf("link down\n"); (void)uu_unlock(uucplock); exit(3); } setbuf(stdout, NULL); loginit(); /* * Now that we have the logfile and the ACU open * return to the real uid and gid. These things will * be closed on exit. Swap real and effective uid's * so we can get the original permissions back * for removing the uucp lock. */ user_uid(); /* * Kludge, their's no easy way to get the initialization * in the right order, so force it here */ if ((PH = getenv("PHONES")) == NOSTR) PH = _PATH_PHONES; vinit(); /* init variables */ setparity("none"); /* set the parity table */ /* * Hardwired connections require the * line speed set before they make any transmissions * (this is particularly true of things like a DF03-AC) */ if (HW && ttysetup(number(value(BAUDRATE)))) { fprintf(stderr, "%s: bad baud rate %ld\n", __progname, number(value(BAUDRATE))); daemon_uid(); (void)uu_unlock(uucplock); exit(3); } if ((p = con())) { printf("\07%s\n[EOT]\n", p); daemon_uid(); (void)uu_unlock(uucplock); exit(1); } if (!HW && ttysetup(number(value(BAUDRATE)))) { fprintf(stderr, "%s: bad baud rate %ld\n", __progname, number(value(BAUDRATE))); daemon_uid(); (void)uu_unlock(uucplock); exit(3); } cucommon: /* * From here down the code is shared with * the "cu" version of tip. */ i = fcntl(FD, F_GETFL); if (i == -1) { perror("fcntl"); cleanup(0); } i = fcntl(FD, F_SETFL, i & ~O_NONBLOCK); if (i == -1) { perror("fcntl"); cleanup(0); } tcgetattr(0, &defterm); gotdefterm = 1; term = defterm; term.c_lflag &= ~(ICANON|IEXTEN|ECHO); term.c_iflag &= ~(INPCK|ICRNL); term.c_oflag &= ~OPOST; term.c_cc[VMIN] = 1; term.c_cc[VTIME] = 0; defchars = term; term.c_cc[VINTR] = term.c_cc[VQUIT] = term.c_cc[VSUSP] = term.c_cc[VDSUSP] = term.c_cc[VDISCARD] = term.c_cc[VLNEXT] = _POSIX_VDISABLE; raw(); pipe(fildes); pipe(repdes); (void)signal(SIGALRM, timeout); if (value(LINEDISC) != TTYDISC) { int ld = (int)(intptr_t)value(LINEDISC); ioctl(FD, TIOCSETD, &ld); } /* * Everything's set up now: * connection established (hardwired or dialup) * line conditioned (baud rate, mode, etc.) * internal data structures (variables) * so, fork one process for local side and one for remote. */ printf(cumode ? "Connected\r\n" : "\07connected\r\n"); tipin_pid = getpid(); if ((tipout_pid = fork())) tipin(); else tipout(); /*NOTREACHED*/ exit(0); }
/* * Botch the interface to look like cu's */ void cumain(int argc, char *argv[]) { int ch, i, parity; long l; char *cp; static char sbuf[12]; if (argc < 2) cuusage(); CU = DV = NOSTR; BR = DEFBR; parity = 0; /* none */ /* * We want to accept -# as a speed. It's easiest to look through * the arguments, replace -# with -s#, and let getopt() handle it. */ for (i = 1; i < argc; i++) { if (argv[i][0] == '-' && argv[i][1] >= '0' && argv[i][1] <= '9') { asprintf(&cp, "-s%s", argv[i] + 1); if (cp == NULL) { fprintf(stderr, "%s: cannot convert -# to -s#\n", __progname); exit(3); } argv[i] = cp; } } while ((ch = getopt(argc, argv, "a:l:s:htoe")) != -1) { switch (ch) { case 'a': CU = optarg; break; case 'l': if (DV != NULL) { fprintf(stderr, "%s: cannot specificy multiple -l options\n", __progname); exit(3); } if (strchr(optarg, '/')) DV = optarg; else asprintf(&DV, "/dev/%s", optarg); break; case 's': l = strtol(optarg, &cp, 10); if (*cp != '\0' || l < 0 || l >= INT_MAX) { fprintf(stderr, "%s: unsupported speed %s\n", __progname, optarg); exit(3); } BR = (int)l; break; case 'h': setboolean(value(LECHO), TRUE); HD = TRUE; break; case 't': HW = 1, DU = -1; break; case 'o': if (parity != 0) parity = 0; /* -e -o */ else parity = 1; /* odd */ break; case 'e': if (parity != 0) parity = 0; /* -o -e */ else parity = -1; /* even */ break; default: cuusage(); break; } } argc -= optind; argv += optind; switch (argc) { case 1: PN = argv[0]; break; case 0: break; default: cuusage(); break; } signal(SIGINT, cleanup); signal(SIGQUIT, cleanup); signal(SIGHUP, cleanup); signal(SIGTERM, cleanup); signal(SIGCHLD, SIG_DFL); /* * The "cu" host name is used to define the * attributes of the generic dialer. */ (void)snprintf(sbuf, sizeof(sbuf), "cu%ld", BR); if ((i = hunt(sbuf)) == 0) { printf("all ports busy\n"); exit(3); } if (i == -1) { printf("link down\n"); (void)uu_unlock(uucplock); exit(3); } setbuf(stdout, NULL); loginit(); user_uid(); vinit(); switch (parity) { case -1: setparity("even"); break; case 1: setparity("odd"); break; default: setparity("none"); break; } setboolean(value(VERBOSE), FALSE); if (HW && ttysetup(BR)) { fprintf(stderr, "%s: unsupported speed %ld\n", __progname, BR); daemon_uid(); (void)uu_unlock(uucplock); exit(3); } if (con()) { printf("Connect failed\n"); daemon_uid(); (void)uu_unlock(uucplock); exit(1); } if (!HW && ttysetup(BR)) { fprintf(stderr, "%s: unsupported speed %ld\n", __progname, BR); daemon_uid(); (void)uu_unlock(uucplock); exit(3); } }
int main(int argc, char **argv) { address_tuple_t tuple; char *server = NULL; char *port = NULL; char *keyfile = NULL; char *pidfile = NULL; char *logfile = NULL; char *progname; char c; char buf[BUFSIZ]; extern char build_info[]; pideid = NULL; progname = argv[0]; while ((c = getopt(argc, argv, "s:p:e:l:dk:i:Vu:N:")) != -1) { switch (c) { case 'd': debug++; break; case 's': server = optarg; break; case 'p': port = optarg; break; case 'e': pideid = optarg; break; case 'i': pidfile = optarg; break; case 'l': logfile = optarg; break; case 'k': keyfile = optarg; break; case 'u': swapper = optarg; break; case 'N': nodelocal_dir = optarg; break; case 'V': fprintf(stderr, "%s\n", build_info); exit(0); break; default: usage(progname); } } if (!pideid) usage(progname); if (debug) loginit(0, 0); else { if (logfile) loginit(0, logfile); else loginit(1, "linktest"); /* See below for daemonization */ } /* * Convert server/port to elvin thing. * * XXX This elvin string stuff should be moved down a layer. */ if (server) { snprintf(buf, sizeof(buf), "elvin://%s%s%s", server, (port ? ":" : ""), (port ? port : "")); server = buf; } /* * Construct an address tuple for subscribing to events for * this node. */ tuple = address_tuple_alloc(); if (tuple == NULL) { fatal("could not allocate an address tuple"); } /* * Ask for just the events we care about. */ tuple->expt = pideid; tuple->objtype = TBDB_OBJECTTYPE_LINKTEST; tuple->eventtype = TBDB_EVENTTYPE_START "," TBDB_EVENTTYPE_KILL; /* * Register with the event system. */ handle = event_register_withkeyfile(server, 0, keyfile); if (handle == NULL) { fatal("could not register with event system"); } /* * Subscribe to the event we specified above. */ if (! event_subscribe(handle, callback, tuple, NULL)) { fatal("could not subscribe to event"); } tuple->objtype = TBDB_OBJECTTYPE_TIME; tuple->objname = ADDRESSTUPLE_ANY; tuple->eventtype = TBDB_EVENTTYPE_START; /* * Subscribe to the TIME start event we specified above. */ if (! event_subscribe(handle, start_callback, tuple, NULL)) { fatal("could not subscribe to event"); } /* * Do this now, once we have had a chance to fail on the above * event system calls. */ if (!debug) daemon(0, 1); /* * Write out a pidfile if root (after we daemonize). */ if (!getuid()) { FILE *fp; if (pidfile) strcpy(buf, pidfile); else sprintf(buf, "%s/linktest.pid", _PATH_VARRUN); fp = fopen(buf, "w"); if (fp != NULL) { fprintf(fp, "%d\n", getpid()); (void) fclose(fp); } } /* * Initialize variables used to control child execution */ locked = FALSE; if(signal(SIGCHLD,sigchld_handler) == SIG_ERR) { fatal("could not install child handler"); } /* * Begin the event loop, waiting to receive event notifications: */ event_main(handle); /* * Unregister with the event system: */ if (event_unregister(handle) == 0) { fatal("could not unregister with event system"); } return 0; }
int main(int argc, char **argv) { loginit(LEVEL_TRACE); /* parse command line */ std::string indir; Argv opts; opts.addBoolOption("recusive,r","recursive the directory"); opts.startGroup("Hidden",false); opts.addTextOption("inputdir,d","directory for scan").setOptionPostion("inputdir,d",1); opts.stopGroup(); if (!opts.parse(argc,argv)) { /* command options parsing error */ opts.showHelp(std::cout); LOG(error)<< "Input error"; return 1; } else { indir=opts.getTextOption("inputdir",""); } if (indir.size()<1) { /* inputdir isnot specified */ opts.showHelp(std::cout,true); LOG(error)<< "Directory must be specified"; return 1; } LOG(trace)<< "Current Path:"<<bfs::current_path().generic_string(); LOG(trace)<< "Input directory:"<<indir; bfs::path p(indir); bfs::path fullp; /* checek input directory */ if (!bfs::exists(p)) { LOG(error)<<"Not exists"; return 1; } else { if (!bfs::is_directory(p)) { LOG(error)<<"Not a directory"; return 1; } else { /* bfs::absolute will remain '..' or '.' */ fullp=bfs::canonical(p); LOG(trace)<<"Full path:"<<fullp.generic_string(); } } /* list files */ walk(fullp,item_action,opts.getBoolOption("recusive")); /* generate a unique filename, used for temperary file */ std::cout<<bfs::unique_path().generic_string()<<std::endl; /* make dir */ bfs::path tmpfile("temp/abc/def"); /* path.parent_path() must exist for bfs::create_directory(path) */ /* makedirs(path) will call create_directory() repeatly until path is created */ makedirs(tmpfile); /* create a temperary file */ tmpfile/=bfs::unique_path(); LOG(trace)<<tmpfile.generic_string(); std::ofstream ofs(tmpfile.generic_string()); ofs<<"test\n"; ofs.close(); /* remove directory */ bfs::remove_all("temp"); /* other file operation: * copy, copy_directory, copy_file, copy_symlink * copy will automaticall choose copy_directory/copy_file/copy_symlink * remove, remove_all * remove for file, remove_all for directory * rename */ std::vector<bfs::path> vec; findInPath("vim",{"."},vec); std::copy(vec.cbegin(),vec.cend(),std::ostream_iterator<bfs::path>(std::cout,"\n")); return 0; }
/* * Initialization code. * Called from cold start routine as * soon as a stack and segmentation * have been established. * Functions: * clear and free user core * turn on clock * hand craft 0th process * call all initialization routines * fork - process 0 to schedule * - process 1 execute bootstrap */ int main() { register struct proc *p; register int i; register struct fs *fs = NULL; char inbuf[4]; char inch; int s __attribute__((unused)); startup(); printf ("\n%s", version); cpuidentify(); cnidentify(); /* * Set up system process 0 (swapper). */ p = &proc[0]; p->p_addr = (size_t) &u; p->p_stat = SRUN; p->p_flag |= SLOAD | SSYS; p->p_nice = NZERO; u.u_procp = p; /* init user structure */ u.u_cmask = CMASK; u.u_lastfile = -1; for (i = 1; i < NGROUPS; i++) u.u_groups[i] = NOGROUP; for (i = 0; i < sizeof(u.u_rlimit)/sizeof(u.u_rlimit[0]); i++) u.u_rlimit[i].rlim_cur = u.u_rlimit[i].rlim_max = RLIM_INFINITY; /* Initialize signal state for process 0 */ siginit (p); /* * Initialize tables, protocols, and set up well-known inodes. */ #ifdef LOG_ENABLED loginit(); #endif coutinit(); cinit(); pqinit(); ihinit(); bhinit(); binit(); nchinit(); clkstart(); s = spl0(); rdisk_init(); pipedev = rootdev = get_boot_device(); swapdev = get_swap_device(); /* Mount a root filesystem. */ for (;;) { if(rootdev!=-1) { fs = mountfs (rootdev, (boothowto & RB_RDONLY) ? MNT_RDONLY : 0, (struct inode*) 0); } if (fs) break; printf ("No root filesystem available!\n"); // rdisk_list_partitions(RDISK_FS); retry: printf ("Please enter device to boot from (press ? to list): "); inch=0; inbuf[0] = inbuf[1] = inbuf[2] = inbuf[3] = 0; while((inch=cngetc()) != '\r') { switch(inch) { case '?': printf("?\n"); rdisk_list_partitions(RDISK_FS); printf ("Please enter device to boot from (press ? to list): "); break; default: printf("%c",inch); inbuf[0] = inbuf[1]; inbuf[1] = inbuf[2]; inbuf[2] = inbuf[3]; inbuf[3] = inch; break; } } inch = 0; if(inbuf[0]=='r' && inbuf[1]=='d') { if(inbuf[2]>='0' && inbuf[2] < '0'+rdisk_num_disks()) { if(inbuf[3]>='a' && inbuf[3]<='d') { rootdev=makedev(inbuf[2]-'0',inbuf[3]-'a'+1); inch = 1; } } } else if(inbuf[1]=='r' && inbuf[2]=='d') { if(inbuf[3]>='0' && inbuf[3] < '0'+rdisk_num_disks()) { rootdev=makedev(inbuf[3]-'0',0); inch = 1; } } else if(inbuf[3] == 0) { inch = 1; } if(inch==0) { printf("\nUnknown device.\n\n"); goto retry; } printf ("\n\n"); } printf ("phys mem = %u kbytes\n", physmem / 1024); printf ("user mem = %u kbytes\n", MAXMEM / 1024); if(minor(rootdev)==0) { printf ("root dev = rd%d (%d,%d)\n", major(rootdev), major(rootdev), minor(rootdev) ); } else { printf ("root dev = rd%d%c (%d,%d)\n", major(rootdev), 'a'+minor(rootdev)-1, major(rootdev), minor(rootdev) ); } printf ("root size = %u kbytes\n", fs->fs_fsize * DEV_BSIZE / 1024); mount[0].m_inodp = (struct inode*) 1; /* XXX */ mount_updname (fs, "/", "root", 1, 4); time.tv_sec = fs->fs_time; boottime = time; /* Find a swap file. */ swapstart = 1; while(swapdev == -1) { printf("Please enter swap device (press ? to list): "); inbuf[0] = inbuf[1] = inbuf[2] = inbuf[3] = 0; while((inch = cngetc())!='\r') { switch(inch) { case '?': printf("?\n"); rdisk_list_partitions(RDISK_SWAP); printf("Please enter swap device (press ? to list): "); break; default: printf("%c",inch); inbuf[0] = inbuf[1]; inbuf[1] = inbuf[2]; inbuf[2] = inbuf[3]; inbuf[3] = inch; break; } } inch = 0; if(inbuf[0]=='r' && inbuf[1]=='d') { if(inbuf[2]>='0' && inbuf[2] < '0'+rdisk_num_disks()) { if(inbuf[3]>='a' && inbuf[3]<='d') { swapdev=makedev(inbuf[2]-'0',inbuf[3]-'a'+1); inch = 1; } } } else if(inbuf[1]=='r' && inbuf[2]=='d') { if(inbuf[3]>='0' && inbuf[3] < '0'+rdisk_num_disks()) { swapdev=makedev(inbuf[3]-'0',0); inch = 1; } } if(minor(swapdev)!=0) { if(partition_type(swapdev)!=RDISK_SWAP) { printf("\nNot a swap partition!\n\n"); swapdev=-1; } } } nswap = rdsize(swapdev); if(minor(swapdev)==0) { printf ("swap dev = rd%d (%d,%d)\n", major(swapdev), major(swapdev), minor(swapdev) ); } else { printf ("swap dev = rd%d%c (%d,%d)\n", major(swapdev), 'a'+minor(swapdev)-1, major(swapdev), minor(swapdev) ); } (*bdevsw[major(swapdev)].d_open)(swapdev, FREAD|FWRITE, S_IFBLK); printf ("swap size = %u kbytes\n", nswap * DEV_BSIZE / 1024); if (nswap <= 0) panic ("zero swap size"); /* don't want to panic, but what ? */ mfree (swapmap, nswap, swapstart); /* Kick off timeout driven events by calling first time. */ schedcpu (0); /* Set up the root file system. */ rootdir = iget (rootdev, &mount[0].m_filsys, (ino_t) ROOTINO); iunlock (rootdir); u.u_cdir = iget (rootdev, &mount[0].m_filsys, (ino_t) ROOTINO); iunlock (u.u_cdir); u.u_rdir = NULL; /* * Make init process. */ if (newproc (0) == 0) { /* Parent process with pid 0: swapper. * No return from sched. */ sched(); } /* Child process with pid 1: init. */ s = splhigh(); p = u.u_procp; p->p_dsize = icodeend - icode; p->p_daddr = USER_DATA_START; p->p_ssize = 1024; /* one kbyte of stack */ p->p_saddr = USER_DATA_END - 1024; bcopy ((caddr_t) icode, (caddr_t) USER_DATA_START, icodeend - icode); /* * return goes to location 0 of user init code * just copied out. */ return 0; }
/* main entry point */ int main (int argc, char ** argv) { char * infile = NULL, * outfile = NULL, * input = NULL, * output = NULL; loginit (); precinit (); // check program arguments for (int i = 1; i < argc; i++) { if (!strcmp (argv[i], "-v") || !strcmp (argv[i], "--version")) { fprintf (stdout, "QucsConverter " PACKAGE_VERSION "\n" "Copyright (C) 2004, 2005, 2006, 2007 Stefan Jahn <*****@*****.**>\n" "\nThis is free software; see the source for copying " "conditions. There is NO\n" "warranty; not even for MERCHANTABILITY or FITNESS FOR A " "PARTICULAR PURPOSE.\n"); return 0; } if (!strcmp (argv[i], "-h") || !strcmp (argv[i], "--help")) { fprintf (stdout, "Usage: %s [OPTION]...\n\n" " -h, --help display this help and exit\n" " -v, --version display version information and exit\n" " -i FILENAME use file as input file (default stdin)\n" " -o FILENAME use file as output file (default stdout)\n" " -if FORMAT input data specification (e.g. spice)\n" " -of FORMAT output data specification (e.g. qucs)\n" " -a, --noaction do not include netlist actions in the output\n" " -g GNDNODE replace ground node\n" " -d DATANAME data variable specification\n" " -c, --correct enable node correction\n" "\nReport bugs to <" PACKAGE_BUGREPORT ">.\n", argv[0]); return 0; } else if (!strcmp (argv[i], "-i")) { infile = argv[++i]; } else if (!strcmp (argv[i], "-o")) { outfile = argv[++i]; } else if (!strcmp (argv[i], "-if")) { input = argv[++i]; } else if (!strcmp (argv[i], "-of")) { output = argv[++i]; } else if (!strcmp (argv[i], "-a") || !strcmp (argv[i], "--noaction")) { qucs_actions = 0; } else if (!strcmp (argv[i], "-g")) { if (argv[++i]) qucs_gnd = argv[i]; } else if (!strcmp (argv[i], "-d")) { if (argv[++i]) data_var = argv[i]; } else if (!strcmp (argv[i], "-c") || !strcmp (argv[i], "--correct")) { vcd_correct = 1; } } // check input/output formats int infound = 0; int outfound = 0; for (int j = 0; actionset[j].in != NULL; j++) { int in = 0, out = 0; if (input && !strcmp (input, actionset[j].in)) { in = infound = 1; } if (output && !strcmp (output, actionset[j].out)) { out = outfound = 1; } if (in && out) { return actionset[j].execute (&actionset[j], infile, outfile); } } // no appropriate conversion found if (!infound) { fprintf (stderr, "invalid input data specification `%s'\n", input ? input : "not given"); } if (!outfound) { fprintf (stderr, "invalid output data specification `%s'\n", output ? output : "not given"); } fprintf (stderr, "invalid input/output data specification `%s->%s'\n", input ? input : "not given", output ? output : "not given"); return -1; }
struct OPTION *setOPTION(int argc, char **argv) { if (argc == 1) display_usage(); struct OPTION *op = smalloc(sizeof(struct OPTION)); init_OPTION(op); static const char *short_options = "ho:s:lLcdC:A:"; struct option long_options[] = { {"help", no_argument, NULL, 'h'}, {"log-file", required_argument, NULL, 'o'}, {"num-randomseed", required_argument, NULL, 's'}, {"ds-line", no_argument, NULL, 'l'}, {"num-line-node", required_argument, NULL, 300}, {"ds-lattice", no_argument, NULL, 'L'}, {"num-lattice-side", required_argument, NULL, 301}, {"ds-crossover", no_argument, NULL, 'c'}, {"ds-direct", no_argument, NULL, 'd'}, {"rate-infect", required_argument, NULL, 302}, {"rate-recover", required_argument, NULL, 303}, {"STEP", required_argument, NULL, 304}, {0, 0, 0, 0}, }; int longIndex = 0; int opt; do { opt = getopt_long(argc, argv, short_options, long_options, &longIndex); if (opt == -1) break; switch (opt) { case 'h': display_usage(); break; case 'o': op->logfilename = optarg; break; case 's': op->num_randomseed = strtol(optarg, NULL, 10); break; case 'l': op->ds_line = true; break; case 300: op->num_line_node = strtol(optarg, NULL, 10); break; case 'L': op->ds_lattice = true; break; case 301: op->num_lattice_side = strtol(optarg, NULL, 10); break; case 'c': op->ds_crossover = true; break; case 'd': op->ds_direct = true; break; case 302: op->rate_infect = strtod(optarg, NULL); break; case 303: op->rate_recover = strtod(optarg, NULL); break; case 304: op->STEP = strtol(optarg, NULL, 10); break; case '?': break; default: abort(); } } while (1); loginit(op->logfilename, getloglevel()); setRGseed(op->num_randomseed); verify_OPTION(op); info_OPTION(op); return op; }
static void parseopts(int argc, char *argv[]) { static const struct option long_options[] = { { "config", 1, 0, 'c' }, { "syslog", 0, 0, 's' }, { "nosimd", 0, 0, 'S' }, { "daemonize", 0, 0, 'D' }, { 0, 0, 0, 0 } }; char *configname = NULL, *cfgname, *filename = "/etc/ax25/soundmodem.conf"; unsigned int verblevel = 2, tosyslog = 0, simd = 1, schedrr = 0, lockmem = 0, daemonize = 0; int c, err = 0; xmlDocPtr doc; xmlNodePtr node; int pfds[2]; pid_t pid; unsigned char uch; while ((c = getopt_long(argc, argv, "v:sSc:RD" MLOCKOPT, long_options, NULL)) != EOF) { switch (c) { case 'v': verblevel = strtoul(optarg, NULL, 0); break; case 's': tosyslog = 1; break; case 'S': simd = 0; break; case 'c': configname = optarg; break; case 'R': schedrr = 1; break; #ifdef HAVE_MLOCKALL case 'M': lockmem = 1; break; #endif /* HAVE_MLOCKALL */ case 'D': daemonize = 1; break; default: err++; break; } } if (err) { fprintf(stderr, "usage: [-v <verblevel>] [-s] [-S] [-R]" MLOCKHLP " [-c <configname>] <configfile>\n"); exit(1); } loginit(verblevel, tosyslog); if (daemonize) { if (pipe(pfds)) logerr(MLOG_FATAL, "pipe"); switch (pid = fork()) { case -1: logerr(MLOG_FATAL, "fork"); case 0: /* child process */ close(pfds[0]); setsid(); /* become a process group leader and drop controlling terminal */ fclose(stdin); /* no more standard in */ break; default: /* parent process */ close(pfds[1]); err = read(pfds[0], &uch, sizeof(uch)); if (err != sizeof(uch)) logprintf(MLOG_FATAL, "SoundModem init failed\n"); exit(0); } } initsimd(simd); #if 0 if (optind >= argc) logprintf(MLOG_FATAL, "no configuration file specified\n"); #endif if (optind < argc) filename = argv[optind]; doc = xmlParseFile(filename); if (!doc || !doc->root || !doc->root->name) logprintf(MLOG_FATAL, "Error parsing config file \"%s\"\n", filename); if (strcmp(doc->root->name, "modem")) logprintf(MLOG_FATAL, "Config file does not contain modem data\n"); for (node = doc->root->childs; node; node = node->next) { if (!node->name || strcmp(node->name, "configuration")) continue; if (!configname) break; cfgname = xmlGetProp(node, "name"); if (cfgname && !strcmp(cfgname, configname)) break; } if (!node) logprintf(MLOG_FATAL, "Configuartion not found\n"); if (!node->childs) logprintf(MLOG_FATAL, "Configuration empty\n"); err = parsecfg(doc, node->childs, &state, &schedrr); xmlFreeDoc(doc); if (err) exit(1); /* * lock memory down */ #ifdef HAVE_MLOCKALL if (lockmem) { if (mlockall(MCL_CURRENT | MCL_FUTURE) == -1) logerr(MLOG_ERROR, "mlockall"); } #endif /* HAVE_MLOCKALL */ #ifdef HAVE_SCHED_H if (schedrr) { struct sched_param schp; memset(&schp, 0, sizeof(schp)); schp.sched_priority = sched_get_priority_min(SCHED_RR)+1; if (sched_setscheduler(0, SCHED_RR, &schp) != 0) logerr(MLOG_ERROR, "sched_setscheduler"); } #endif /* HAVE_SCHED_H */ if (daemonize) { uch = 0; if (write(pfds[1], &uch, sizeof(uch)) != sizeof(uch)) logerr(MLOG_ERROR, "write"); close(pfds[1]); } }
int main(int argc, char **argv) { int tcpsock, udpsock, i, ch; unsigned int maxfd; FILE *fp; char buf[BUFSIZ]; #ifndef NO_EMULAB extern char build_info[]; #endif fd_set fds, sfds; char *logfile = (char *) NULL; struct sigaction sa; while ((ch = getopt(argc, argv, "hVdp:vl:")) != -1) switch(ch) { case 'l': if (strlen(optarg) > 0) { logfile = optarg; } break; case 'p': if (sscanf(optarg, "%d", &portnum) == 0) { fprintf(stderr, "Error: -p value is not a number: " "%s\n", optarg); usage(); } else if ((portnum <= 0) || (portnum >= 65536)) { fprintf(stderr, "Error: -p value is not between " "0 and 65536: %d\n", portnum); usage(); } break; case 'd': debug++; case 'v': verbose++; break; case 'V': #ifndef NO_EMULAB fprintf(stderr, "%s\n", build_info); #else fprintf(stderr, "Built in standalone mode\n"); #endif exit(0); break; case 'h': case '?': default: usage(); } argc -= optind; argv += optind; if (argc) { fprintf(stderr, "Error: Unrecognized command line arguments: %s ...\n", argv[0]); usage(); } #ifndef NO_EMULAB if (debug) loginit(0, logfile); else { if (logfile) loginit(0, logfile); else loginit(1, "syncd"); } #endif info("daemon starting (version %d)\n", CURRENT_VERSION); #ifndef NO_EMULAB info("%s\n", build_info); #endif /* * Create TCP/UDP server. */ if (makesockets(&portnum, &udpsock, &tcpsock) < 0) { error("Could not make sockets!"); exit(1); } /* * Register with tmcc */ #ifndef NO_EMULAB if (PortRegister(SERVER_SERVNAME, portnum) < 0) { error("Could not register service with tmcd!"); exit(1); } #endif /* Now become a daemon */ if (!debug) daemon(0, 1); signal(SIGUSR1, setverbose); signal(SIGUSR2, setverbose); sa.sa_handler = handle_sighup; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; // XXX No SA_RESTART, we want the select to break... sigaction(SIGHUP, &sa, NULL); #if defined(SIGINFO) sa.sa_handler = handle_siginfo; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGINFO, &sa, NULL); #endif /* * Stash the pid away. */ if (!geteuid()) { sprintf(buf, "%s/syncd.pid", _PATH_VARRUN); fp = fopen(buf, "w"); if (fp != NULL) { fprintf(fp, "%d\n", getpid()); (void) fclose(fp); } } /* * Now sit and listen for connections. */ FD_ZERO(&sfds); FD_SET(tcpsock, &sfds); tcpsockets[tcpsock].barrier = (barrier_ctrl_t *)-1; /* sentinel */ FD_SET(udpsock, &sfds); tcpsockets[udpsock].barrier = (barrier_ctrl_t *)-1; /* sentinel */ maxfd = tcpsock; if (udpsock > tcpsock) maxfd = udpsock; while (1) { struct sockaddr_in client; int cc, newsock, j; socklen_t length; barrier_req_t barrier_req; if (gotsiginfo) { print_barriers(); gotsiginfo = 0; } if (gotsighup) { clear_barriers(); maxfd = maxtcpsocket(&sfds, maxfd); gotsighup = 0; } fds = sfds; errno = 0; i = select(maxfd + 1, &fds, NULL, NULL, NULL); if (i < 0) { if (errno == EINTR) { if (!gotsiginfo && !gotsighup) { warning("select interrupted, " "continuing"); } continue; } fatal("select: %s", strerror(errno)); } if (i == 0) continue; if (FD_ISSET(tcpsock, &fds)) { FD_CLR(tcpsock, &fds); i -= 1; length = sizeof(client); newsock = accept(tcpsock, (struct sockaddr *)&client, &length); if (newsock < 0) { errorc("accepting TCP connection"); continue; } if ((cc = readall(newsock, &barrier_req, sizeof(barrier_req))) <= 0) { if (cc < 0) errorc("Reading TCP request"); error("TCP connection aborted\n"); close(newsock); continue; } if (handle_request(newsock, &client, &barrier_req, 1) != 0) { /* There was an error while processing. */ close(newsock); } else if (tcpsockets[newsock].barrier != NULL) { /* * The barrier was not crossed, add a * check for readability so we can detect * a closed connection. */ FD_SET(newsock, &sfds); fcntl(newsock, F_SETFL, O_NONBLOCK); if (newsock > maxfd) maxfd = newsock; } else { /* * The barrier was crossed and the socket * closed, update maxfd. */ maxfd = maxtcpsocket(&sfds, maxfd); } } if (FD_ISSET(udpsock, &fds)) { FD_CLR(udpsock, &fds); i -= 1; length = sizeof(client); cc = recvfrom(udpsock, &barrier_req, sizeof(barrier_req), 0, (struct sockaddr *)&client, &length); if (cc <= 0) { if (cc < 0) errorc("Reading UDP request"); error("UDP Connection aborted\n"); continue; } handle_request(udpsock, &client, &barrier_req, 0); } /* Check other active FDs for garbage/closed connections. */ for (j = 0; i > 0; j++) { char scratch[1024]; if (FD_ISSET(j, &fds)) { i -= 1; while ((cc = read(j, scratch, sizeof(scratch))) > 0) { /* Nothing to do... */ } if( cc == 0 ) { /* Connection closed */ FD_CLR(j, &sfds); close(j); remove_tcpclient(j); if( j == maxfd ) { maxfd = maxtcpsocket(&sfds, maxfd); } } } } } close(tcpsock); close(udpsock); info("daemon terminating\n"); exit(0); }