int main(int argc, char *argv[]) { char c; int i=0; nonblock(NB_ENABLE); while(!i) { usleep(1); i=kbhit(); if (i!=0) { c=fgetc(stdin); if (c=='q') { i=1; } else { i=0; } } fprintf(stderr,"%d ",i); } printf("\n you hit %c. \n",c); nonblock(NB_DISABLE); return 0; } /* main */
static void tls_exec_server(const char *user, int startfd, const char *privkey, const char *cert, int debuglevel) { SSL_CTX *sslctx; SSL *ssl; int sockfd, tcpfd, ret; pjdlog_debug_set(debuglevel); pjdlog_prefix_set("[TLS sandbox] (server) "); #ifdef HAVE_SETPROCTITLE setproctitle("[TLS sandbox] (server) "); #endif sockfd = startfd; tcpfd = startfd + 1; SSL_load_error_strings(); SSL_library_init(); sslctx = SSL_CTX_new(TLSv1_server_method()); if (sslctx == NULL) pjdlog_exitx(EX_TEMPFAIL, "SSL_CTX_new() failed."); SSL_CTX_set_options(sslctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3); ssl = SSL_new(sslctx); if (ssl == NULL) pjdlog_exitx(EX_TEMPFAIL, "SSL_new() failed."); if (SSL_use_RSAPrivateKey_file(ssl, privkey, SSL_FILETYPE_PEM) != 1) { ssl_log_errors(); pjdlog_exitx(EX_CONFIG, "SSL_use_RSAPrivateKey_file(%s) failed.", privkey); } if (SSL_use_certificate_file(ssl, cert, SSL_FILETYPE_PEM) != 1) { ssl_log_errors(); pjdlog_exitx(EX_CONFIG, "SSL_use_certificate_file(%s) failed.", cert); } if (sandbox(user, true, "proto_tls server") != 0) pjdlog_exitx(EX_CONFIG, "Unable to sandbox TLS server."); pjdlog_debug(1, "Privileges successfully dropped."); nonblock(sockfd); nonblock(tcpfd); if (SSL_set_fd(ssl, tcpfd) != 1) pjdlog_exitx(EX_TEMPFAIL, "SSL_set_fd() failed."); ret = SSL_accept(ssl); ssl_check_error(ssl, ret); tls_loop(sockfd, ssl); }
bool Socket::listen() { int _backLog = 128; if (!_isServer){ return false; } if (!checkSock()) { return false; } int value = 1; nonblock(_fd); setsockopt(_fd, SOL_SOCKET, SO_REUSEADDR, (const void *)(&value), sizeof(value)); if (::bind(_fd, (struct sockaddr *)&_address, sizeof(_address)) < 0) { return false; } if (::listen(_fd, _backLog) < 0) { return false; } return true; }
int new_connection(int s) { struct sockaddr_in isa; /* struct sockaddr peer; */ int i; int t; char buf[100]; i = sizeof(isa); getsockname(s, &isa, &i); if ((t = accept(s, &isa, &i)) < 0) { perror("Accept"); return(-1); } nonblock(t); /* i = sizeof(peer); if (!getpeername(t, &peer, &i)) { *(peer.sa_data + 49) = '\0'; sprintf(buf, "New connection from addr %s\n", peer.sa_data); log(buf); } */ return(t); }
void start_connect(struct connection *c) { c->read = 0; c->bread = 0; c->keepalive = 0; c->cbx = 0; c->gotheader = 0; c->fd = socket(AF_INET, SOCK_STREAM, 0); if(c->fd<0) err("socket"); nonblock(c->fd); gettimeofday(&c->start,0); if(connect(c->fd, (struct sockaddr *) &server, sizeof(server))<0) { if(errno==EINPROGRESS) { c->state = STATE_CONNECTING; FD_SET(c->fd, &writebits); return; } else { close(c->fd); err_conn++; if(bad++>10) { printf("\nTest aborted after 10 failures\n\n"); exit(1); } start_connect(c); } } /* connected first time */ write_request(c); }
int getcmd(struct cmd *cmd) { size_t j; int c; assert(cmd != NULL && cmd->i >= 0 && cmd->i <= CMDMAX); if (cmd->f == NULL) return CDONE; if (cmd->conn == 0) nonblock(fileno(cmd->f)); loop: do { while ((c = fgetc(cmd->f)) != EOF && !isspace(c)) if (cmd->i < CMDMAX) cmd->buffer[cmd->i++] = toupper(c); if (c == EOF) { if (ferror(cmd->f) && errno == EIO) { cmd->conn = 1; cmd->i = 0; } clearerr(cmd->f); return CDONE; } } while (cmd->i == 0); cmd->conn = 1; if (cmd->i >= CMDMAX) { cmd->i = 0; return CINVALID; } cmd->buffer[cmd->i] = '\0'; for (j = 0; ctable[j].type != CINVALID; j++) if (strcmp(ctable[j].command, cmd->buffer) == 0) break; cmd->i = 0; return ctable[j].type; }
static void report_accept(struct silly_socket *ss, struct socket *listen) { const char *str; struct socket *s; struct sockaddr_in addr; struct silly_message_socket *sa; char buff[INET_ADDRSTRLEN]; assert(ADDRLEN >= INET_ADDRSTRLEN + 8); socklen_t len = sizeof(struct sockaddr); int fd = accept(listen->fd, (struct sockaddr *)&addr, &len); if (fd < 0) return ; sa = silly_malloc(sizeof(*sa) + ADDRLEN); sa->data = (uint8_t *)(sa + 1); sa->type = SILLY_SACCEPT; str = inet_ntop(addr.sin_family, &addr.sin_addr, buff, sizeof(buff)); snprintf((char *)sa->data, ADDRLEN, "%s:%d", str, ntohs(addr.sin_port)); nonblock(fd); keepalive(fd); nodelay(fd); s = newsocket(ss, NULL, fd, STYPE_SOCKET, NULL); if (s == NULL) return; sa->sid = s->sid; sa->ud = listen->sid; silly_worker_push(tocommon(sa)); return ; }
int silly_socket_udpbind(const char *ip, uint16_t port) { int fd; int err; struct socket *s; struct cmdpacket cmd; fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd < 0) return -1; err = bindfd(fd, ip, port); if (err < 0) goto end; nonblock(fd); s = allocsocket(SSOCKET, STYPE_ALLOCED, PROTOCOL_UDP); if (s == NULL) { fprintf(stderr, "[socket] udplisten %s:%d allocsocket fail\n", ip, port); goto end; } s->fd = fd; cmd.type = 'B'; cmd.u.listen.sid = s->sid; pipe_blockwrite(SSOCKET->ctrlsendfd, &cmd); return s->sid; end: perror("udplisten"); close(fd); return -1; }
int try_output(int is_stderr) { bufchain *chain = (is_stderr ? &stderr_data : &stdout_data); int fd = (is_stderr ? STDERR_FILENO : STDOUT_FILENO); void *senddata; int sendlen, ret; if (bufchain_size(chain) > 0) { int prev_nonblock = nonblock(fd); do { bufchain_prefix(chain, &senddata, &sendlen); ret = write(fd, senddata, sendlen); if (ret > 0) bufchain_consume(chain, ret); } while (ret == sendlen && bufchain_size(chain) != 0); if (!prev_nonblock) no_nonblock(fd); if (ret < 0 && errno != EAGAIN) { perror(is_stderr ? "stderr: write" : "stdout: write"); exit(1); } } if (outgoingeof == EOF_PENDING && bufchain_size(&stdout_data) == 0) { close(STDOUT_FILENO); outgoingeof = EOF_SENT; } return bufchain_size(&stdout_data) + bufchain_size(&stderr_data); }
int main(void) { struct io_pollfd ifd; struct io_pollfd *rfds; unsigned long len; char buf[4]; check_core(); init_core(&iop); test_assert(io_poll_size(&iop) == 0); verify(&iop); test_assert(pipe(pfd) != -1); test_assert(nonblock(pfd[1]) != -1); test_assert(nonblock(pfd[0]) != -1); /* test for readability */ ifd.events = IO_POLL_READ; ifd.fd = pfd[0]; test_assert(io_poll_add(&iop, &ifd) == 1); /* pipe gets readability */ test_assert(write(pfd[1], "AAAA", 4) == 4); test_assert(io_poll_wait(&iop, 0) == 1); io_poll_rfds(&iop, &rfds, &len); test_assert(len == 1); test_assert(rfds[0].fd == ifd.fd); test_assert(io_poll_got_read(&rfds[0]) == 1); test_assert(read(rfds[0].fd, buf, 4) == 4); test_assert(bin_same(buf, "AAAA", 4) == 1); /* send EOF */ test_assert(close(pfd[1]) != -1); test_assert(io_poll_wait(&iop, 0) == 1); io_poll_rfds(&iop, &rfds, &len); test_assert(len == 1); test_assert(rfds[0].fd == ifd.fd); test_assert(read(rfds[0].fd, buf, 4) == 0 || io_poll_got_eof(&rfds[0]) == 1); test_assert(io_poll_rm(&iop, &ifd) == 1); test_assert(close(pfd[0]) != -1); test_assert(io_poll_free(&iop)); return 0; }
HybridConnection* hybrid_proxy_connect(const gchar *hostname, gint port, connect_callback func, gpointer user_data) { gint sk; struct sockaddr addr; HybridConnection *conn; g_return_val_if_fail(port != 0, NULL); g_return_val_if_fail(hostname != NULL, NULL); hybrid_debug_info("connect", "connecting to %s:%d", hostname, port); conn = g_new0(HybridConnection, 1); if ((sk = socket(AF_INET, SOCK_STREAM, 0)) == -1) { hybrid_debug_error("connect", "create socket: %s", strerror(errno)); hybrid_connection_destroy(conn); return NULL; } if (nonblock(sk) != HYBRID_OK) { hybrid_connection_destroy(conn); return NULL; } if (addr_init(hostname, port, &addr) != HYBRID_OK) { hybrid_connection_destroy(conn); return NULL; } if (connect(sk, &addr, sizeof(addr)) != 0) { if (errno != EINPROGRESS) { hybrid_debug_error("connect", "connect to \'%s:%d\':%s", hostname, port, strerror(errno)); hybrid_connection_destroy(conn); return NULL; } hybrid_debug_info("connect", "connect in progress"); hybrid_event_add(sk, HYBRID_EVENT_WRITE, func, user_data); } else { /* connection establish imediately */ func(sk, user_data); } conn->sk = sk; conn->host = g_strdup(hostname); conn->port = port; return conn; }
/* * Open a UDP connection. */ int udp_open(u_int32_t dst, int sport, int rport, int nonblocking) { int fd; int len; int bufsize; struct sockaddr_in sin; fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd < 0) { perror("socket"); exit(1); } if (nonblocking) nonblock(fd); /* * bind the local host's address to this socket. If that * fails, another process probably has the addresses bound so * just exit. */ memset((char *)&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = htons(rport); if (bind(fd, (struct sockaddr *)&sin, sizeof(sin)) < 0) { perror("bind"); return (-1); } memset((char *)&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = htons(sport); sin.sin_addr.s_addr = dst; if (connect(fd, (struct sockaddr *)&sin, sizeof(sin)) < 0) { perror("connect"); return(-1); } /* * (try to) make the transmit socket buffer size large. */ bufsize = 80 * 1024; if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char *)&bufsize, sizeof(bufsize)) < 0) { bufsize = 48 * 1024; if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char *)&bufsize, sizeof(bufsize)) < 0) perror("SO_SNDBUF"); } bufsize = 80 * 1024; if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char *)&bufsize, sizeof(bufsize)) < 0) { bufsize = 32 * 1024; if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char *)&bufsize, sizeof(bufsize)) < 0) perror("SO_RCVBUF"); } return (fd); }
void monitor() { sfd = tcpSocket(); if (!sfd) die(1,"Could not allocate socket"); if (reuseSocket(sfd)) die(2,"Failed to reuse socket %d",sfd); if (bindSocket(sfd, address, htons(port))) die(3,"Failed to bind to %d.%d.%d.%d:%d",IP(address),port); if (listen(sfd,backlog)) die(4,"Failed to listen on port %d",port); if (nonblock(sfd)<0) die(5,"Failed to set nonblocking on socket %d", sfd); debug("Listening on %d.%d.%d.%d:%d",IP(address),port); }
void die() { fprintf(stderr, "\nCTRL+C pressed, terminating app\n"); if (!g_nosigint) easynmc_stop_app(g_handle); if (isatty(STDIN_FILENO)) nonblock(STDIN_FILENO, 0); exit(0); }
int rtipChannel::open(u_int32_t addr, int port, rcapTraffic* traffic, rcapRequirements* requirements) { u_int32_t local = findifaddr(addr, port); if (local < addr) { rsock_ = openrsock(addr, port, rlcid_); ssock_ = openssock(addr, port, traffic, requirements, slcid_); } else { ssock_ = openssock(addr, port, traffic, requirements, slcid_); rsock_ = openrsock(addr, port, rlcid_); } if (ssock_ >= 0) nonblock(ssock_); if (rsock_ >= 0) nonblock(rsock_); /*XXX*/ dst_ = addr; }
bool Server::run() { int choosen; while(1) { /* wait for a connection */ addrlen = sizeof(peer_name); newsockfd = accept(sockd, (struct sockaddr*)&peer_name,(socklen_t*) &addrlen); if (newsockfd < 0) perror("ERROR on accept"); else{ nonblock(newsockfd); start: pthread_mutex_lock(&new_connection_mutex); choosen=choose_thread(); if( choosen == -1) { pthread_mutex_unlock(&new_connection_mutex); sleep(1); goto start; } if(configuration->getConfigValue(OPT_DEBUG)) fprintf(stdout," new conn - thread choosen: %d - nr. of connections already in queue: %d\n",choosen,threads[choosen].client_count); fflush(stdout); for(int i = 0; i < MAX_CLIENT_PER_THREAD; i++) { if(threads[choosen].clients[i] == 0) { threads[choosen].clients[i] = newsockfd; threads[choosen].client_count++; break; } } pthread_mutex_unlock(&new_connection_mutex); } } return 0; }
static void cleanup(int signal __attribute__((unused))) { if (sl) { /* Switch back to mass storage mode before closing. */ stlink_run(sl); stlink_exit_debug_mode(sl); stlink_close(sl); } printf("\n"); nonblock(0); exit(1); }
int acceptSocket(int fd) { struct sockaddr_in saddr; socklen_t len = sizeof(struct sockaddr_in); int sock = accept(fd,(struct sockaddr*)&saddr,&len); if (sock < 0) return 0; peer = saddr.sin_addr.s_addr; peer_port = saddr.sin_port; debug("Accepting connection from %d.%d.%d.%d:%d",IP(peer),peer_port); nonblock(sock); timeoutSocket(sock,linger); return sock; }
filer::filer(coroutine *c, const char *name) : fd_(-1), cr_(c) { fd_ = open(name, O_LARGEFILE | O_NOATIME); if(fd_ == -1) { int r = cxx::sys::err::get(); std::stringstream msg; msg << "open file \'" << name << "\' failed: "; throw file_error(r, msg.str()); } nonblock(fd_); }
static void control_incoming(int fd, void *p, uintptr_t u) { int nfd; struct control_tcp *c = p; struct control_stream *s; struct poller_item i; struct sockaddr_in sin; socklen_t sinl; next: sinl = sizeof(sin); nfd = accept(fd, (struct sockaddr *) &sin, &sinl); if (nfd == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) return; goto next; } nonblock(nfd); ilog(LOG_INFO, "New control connection from " DF, DP(sin)); s = obj_alloc0("control_stream", sizeof(*s), control_stream_free); s->fd = nfd; s->control = c; s->poller = c->poller; s->inbuf = streambuf_new(c->poller, nfd); s->outbuf = streambuf_new(c->poller, nfd); memcpy(&s->inaddr, &sin, sizeof(s->inaddr)); mutex_init(&s->lock); s->linked = 1; ZERO(i); i.fd = nfd; i.closed = control_stream_closed; i.readable = control_stream_readable; i.writeable = control_stream_writeable; i.timer = control_stream_timer; i.obj = &s->obj; if (poller_add_item(c->poller, &i)) goto fail; mutex_lock(&c->lock); /* let the list steal our own ref */ c->streams = g_list_prepend(c->streams, s); mutex_unlock(&c->lock); goto next; fail: obj_put(s); goto next; }
static void tryconnect(struct silly_socket *ss, struct cmdpacket *cmd) { int err; int fd; struct sockaddr addr; int sid = cmd->u.connect.sid; int port = cmd->u.connect.port; int bport = cmd->u.connect.bport; const char *ip = cmd->u.connect.ip; const char *bip = cmd->u.connect.bip; struct socket *s = &ss->socketpool[HASH(sid)]; assert(s->sid == sid); assert(s->type == STYPE_ALLOCED); tosockaddr(&addr, ip, port); fd = socket(AF_INET, SOCK_STREAM, 0); if (fd >= 0) err = bindfd(fd, bip, bport); if (fd < 0 || err < 0) { const char *fmt = "[socket] bind %s:%d, errno:%d\n"; fprintf(stderr, fmt, bip, bport, errno); if (fd >= 0) close(fd); report_close(ss, s, errno); freesocket(ss, s); return ; } nonblock(fd); keepalive(fd); nodelay(fd); err = connect(fd, &addr, sizeof(addr)); if (err == -1 && errno != EINPROGRESS) { //error const char *fmt = "[socket] tryconnect %s:%d,errno:%d\n"; fprintf(stderr, fmt, ip, port, errno); close(fd); report_close(ss, s, errno); freesocket(ss, s); return ; } else if (err == 0) { //connect s = newsocket(ss, s, fd, STYPE_SOCKET, report_close); if (s != NULL) report_connected(ss, s); return ; } else { //block s = newsocket(ss, s, fd, STYPE_CONNECTING, report_close); if (s != NULL) sp_write_enable(ss->spfd, s->fd, s, 1); } return ; }
int udp_listener_init(struct udp_listener *u, struct poller *p, struct in6_addr ip, u_int16_t port, udp_listener_callback_t func, struct obj *obj) { struct sockaddr_in6 sin; struct poller_item i; struct udp_listener_callback *cb; cb = obj_alloc("udp_listener_callback", sizeof(*cb), NULL); cb->func = func; cb->p = obj_get_o(obj); u->fd = socket(AF_INET6, SOCK_DGRAM, 0); if (u->fd == -1) goto fail; nonblock(u->fd); reuseaddr(u->fd); ipv6only(u->fd, 0); ZERO(sin); sin.sin6_family = AF_INET6; sin.sin6_addr = ip; sin.sin6_port = htons(port); if (bind(u->fd, (struct sockaddr *) &sin, sizeof(sin))) goto fail; ZERO(i); i.fd = u->fd; i.closed = udp_listener_closed; i.readable = udp_listener_incoming; i.obj = &cb->obj; if (poller_add_item(p, &i)) goto fail; return 0; fail: if (u->fd != -1) close(u->fd); obj_put_o(obj); obj_put(cb); return -1; }
int main(int arg,char * argc[]) { pthread_t thread[10]; char buf[100]; int sfd[10]; int n=0,a; while(1) { printf("ENTER THE PORNTO"); scanf("%d",&a); strcpy(buf,""); sprintf(buf,"%d",a); sfd[n]=mkserver(atoi(argc[1]),0,sname); write(sfd[n],buf,strlen(buf)); printf("%d\n",sfd[n]); nonblock(sfd[n]); pthread_create(&thread[n],NULL,READ,(void *)&sfd[n]); n++; } }
void cli_con() { struct sockaddr_in srv; struct hostent *h_name; int clifd; int n; bzero(&srv, sizeof(srv)); srv.sin_family = AF_INET; srv.sin_port = htons(PORT); inet_pton(AF_INET, IP, &srv.sin_addr); if( (clifd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("ERROR clifd\n"); exit(1); } if(connect(clifd, (struct sockaddr *) &srv, sizeof(srv)) < 0) { printf("ERROR connect\n"); exit(1); } nonblock(clifd); for(n = 0; (n < MAX_CLIENT) && (clifd != -1); n++) { if(list[n] == 0) { #ifdef DEBUG printf("connected %d\n", clifd); #endif list[n] = clifd; clifd = -1; } } if(clifd != -1) { printf("list FULL"); } }
int main() { int count = QSIZE/2; int probadd = 50; int probdel = 50; nonblock(NB_ENABLE); printf("Producer-Consumer simulation \n"); printf(" The bar graph shows how full the queue is \n"); printf(" use keys a,z, to adjust producer rate\n"); printf(" use keys s,x, to adjust consumer rate\n"); printf(" use q to exit\n"); printf("----------------------------------\n"); while(1) { int blocked = 0; int rp = random(probadd); //- producer priority int rc = random(probdel); //- consumer priority if (kbhit()) { char c = fgetc(stdin); printf("\b"); //- delete it fflush(0); if (c == 'a') probadd++; if (c == 'z') probadd--; if (c == 's') probdel++; if (c == 'x') probdel--; if (c == 'q') break; probadd = limit(probadd, 40, 60); probdel = limit(probdel, 40, 60); } if (rp) blocked |= QueueAdd(rp, QSIZE); if (rc) blocked |= QueueDel(rc, QSIZE); BarDisplayEx(QueueDepth(), QSIZE, &probadd, &probdel, blocked); usleep(20000); } QueuePrint(); }
int main() { printf("[altair8800]\n"); i8080_init(); // load_mem_file("data/4kbas32.bin", 0); // i8080_jump(0); load_mem_file("data/88dskrom.bin", 0xff00); disk_drive.disk1.fp = fopen("data/cpm63k.dsk", "r+b"); disk_drive.disk2.fp = fopen("data/zork.dsk", "r+b"); disk_drive.nodisk.status = 0xff; i8080_jump(0xff00); nonblock(NB_ENABLE); //keyboard while (1) { i8080_instruction(); //printf("%04x\n",i8080_pc()); //usleep(1000); } }
int client_connect(const char *host, const char *port) { int rc = 0; struct addrinfo *addr = NULL; rc = getaddrinfo(host, port, NULL, &addr); check(rc == 0, "Failed to lookup %s:%s", host, port); int sock = socket(AF_INET, SOCK_STREAM, 0); check(rc == 0, "Connect failed"); rc = connect(sock, addr->ai_addr, addr->ai_addrlen); check(rc == 0, "Connect failed."); rc = nonblock(sock); check(rc == 0, "Can't set nonblock."); freeaddrinfo(addr); return sock; error: freeaddrinfo(addr); return -1; }
static int dolisten(const char *ip, uint16_t port, int backlog) { int err; int fd; int reuse = 1; fd = socket(AF_INET, SOCK_STREAM, 0); if (fd < 0) return -1; setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)); err = bindfd(fd, ip, port); if (err < 0) goto end; nonblock(fd); err = listen(fd, backlog); if (err < 0) goto end; return fd; end: perror("dolisten"); close(fd); return -1; }
int main(int argc, char **argv) { int core = 0; // EASYNMC_CORE_ANY; /* Default - use first available core */ int ret; char* self = "nmrun"; if (argc < 2) usage(argv[0]), exit(1); while (1) { int c; int option_index = 0; c = getopt_long (argc, argv, "c:h", long_options, &option_index); /* Detect the end of the options. */ if (c == -1) break; switch (c) { case 'c': if (strcmp(optarg, "all") == 0) core = -1; else core = atoi(optarg); break; case 'h': usage(argv[0]); exit(1); break; case '?': default: break; } } char* absfile = argv[optind++]; int num_args = argc - optind; char **args = &argv[optind]; uint32_t flags = ABSLOAD_FLAG_DEFAULT; if (g_nostdio) flags &= ~(ABSLOAD_FLAG_STDIO); struct easynmc_handle *h = easynmc_open(core); g_handle = h; if (!h) { fprintf(stderr, "Failed to open core %d\n", core); exit(1); } int state; if ((state = easynmc_core_state(h)) != EASYNMC_CORE_IDLE) { fprintf(stderr, "Core is %s, expecting core to be idle\n", easynmc_state_name(state)); exit(1); } ret = easynmc_load_abs(h, absfile, &entrypoint, flags); if (0!=ret) { fprintf(stderr, "Failed to upload abs file\n"); exit(1); } ret = easynmc_set_args(h, self, num_args, args); if (ret != 0) { fprintf(stderr, "WARN: Failed to set arguments. Not supported by app?\n"); } ret = easynmc_pollmark(h); if (ret != 0) { fprintf(stderr, "Failed to reset polling counter (\n"); exit(1); }; ret = easynmc_start_app(h, entrypoint); if (ret != 0) { fprintf(stderr, "Failed to start app (\n"); exit(1); } ret = 0; if (!g_nosigint) signal(SIGINT, handle_sigint); easynmc_persist_set(h, g_nosigint ? EASYNMC_PERSIST_ENABLE : EASYNMC_PERSIST_DISABLE); if (!g_detach) { fprintf(stderr, "Application now started, hit CTRL+C to %s it\n", g_nosigint ? "detach" : "stop"); ret = run_interactive_console(h); } else { fprintf(stderr, "Application started, detaching\n"); } if (isatty(STDIN_FILENO)) nonblock(STDIN_FILENO, 0); return ret; }
/* DO NOT SAY ANYTHING. Please ;) */ int run_interactive_console(struct easynmc_handle *h) { int i; int ret = 1; struct epoll_event event[3]; struct epoll_event *events; int efd = epoll_create(2); setvbuf(stdin,NULL,_IONBF,0); if (efd == -1) { perror ("epoll_create"); ret = 1; goto errclose; } int flags = fcntl(h->iofd, F_GETFL, 0); fcntl(h->iofd, F_SETFL, flags | O_NONBLOCK); if (!isatty(STDIN_FILENO)) { flags = fcntl(STDIN_FILENO, F_GETFL, 0); fcntl(h->iofd, F_SETFL, flags | O_NONBLOCK); } else { nonblock(STDIN_FILENO, 1); } event[0].data.fd = h->iofd; event[0].events = EPOLLIN | EPOLLOUT | EPOLLET; event[1].data.fd = h->memfd; event[1].events = EPOLLNMI | EPOLLHP | EPOLLET; event[2].data.fd = STDIN_FILENO; event[2].events = EPOLLIN | EPOLLET; for (i = 0; i < 3; i++) { ret = epoll_ctl (efd, EPOLL_CTL_ADD, event[i].data.fd, &event[i]); if (ret == -1) { perror ("epoll_ctl"); ret = 1; goto errclose; } } events = calloc (NUMEVENTS, sizeof event); int can_read_stdin = 0; int can_write_to_nmc = 0; int gotfromstdin = 0; int written_to_nmc = 0; unsigned char tonmc[1024]; while (1) { int num, i; num = epoll_wait(efd, events, NUMEVENTS, -1); for (i = 0; i < num; i++) { if ((events[i].data.fd == STDIN_FILENO) && (events[i].events & EPOLLIN)) can_read_stdin=1; if (can_read_stdin && !gotfromstdin) { gotfromstdin = read(STDIN_FILENO, tonmc, 1024); if (isatty(STDIN_FILENO) && tonmc[0] == 3) die(); if (-1 == gotfromstdin) { perror("read-from-stdin"); return 1; } } if (events[i].data.fd == h->iofd && (events[i].events & EPOLLIN)) { ret = read_inbound(h->iofd); if (ret != 0) return ret; } if (events[i].data.fd == h->iofd && (events[i].events & EPOLLOUT)) can_write_to_nmc++; if ((events[i].data.fd == h->memfd) && easynmc_core_state(h) == EASYNMC_CORE_IDLE) { /* * Read any bytes left in circular buffer. */ ret = read_inbound(h->iofd); if ( ret != 0) return ret; ret = easynmc_exitcode(h); fprintf(stderr, "App terminated with result %d, exiting\n", ret); return ret; } if (can_write_to_nmc && (written_to_nmc != gotfromstdin)) { int n = write(h->iofd, &tonmc[written_to_nmc], gotfromstdin - written_to_nmc); if (n > 0) { written_to_nmc += n; if (written_to_nmc == gotfromstdin) { gotfromstdin = 0; written_to_nmc = 0; } } else if (errno == EAGAIN) { break; } else { perror("write-to-nmc"); return 1; } } } } errclose: easynmc_close(h); return ret; }