Ejemplo n.º 1
0
int
main(int argc, char *argv[]) {

	setlocale(LC_CTYPE, "");

	ARGBEGIN{
	case 'v':
		lprint(2, version);
		return 0;
	default: usage();
	}ARGEND;

	if(argc)
		usage();

	fmtinstall('K', fmtkey);
	initdisplay();

	selectinput(&scr.root, KeyPressMask|KeyReleaseMask);
	sethandler(&scr.root, &handlers);
	if(!grabkeyboard(&scr.root))
		fatal("can't grab keyboard\n");

	if(isatty(1))
		lprint(2, "Please press a key...\n");
	event_loop();
	lprint(1, "%s\n", keyname);

	XCloseDisplay(display);
	return 0;
}
Ejemplo n.º 2
0
void
bar_init(WMScreen *s) {
	WinAttr wa;

	if(s->barwin) {
		bar_resize(s);
		return;
	}

	s->brect = s->r;
	s->brect.min.y = s->brect.max.y - labelh(def.font);

	wa.override_redirect = 1;
	wa.background_pixmap = ParentRelative;
	wa.event_mask = ExposureMask
		      | ButtonPressMask
		      | ButtonReleaseMask
		      | FocusChangeMask;
	s->barwin = createwindow(&scr.root, s->brect, scr.depth, InputOutput,
			&wa, CWOverrideRedirect
			   | CWBackPixmap
			   | CWEventMask);
	s->barwin->aux = s;
	xdnd_initwindow(s->barwin);
	sethandler(s->barwin, &handlers);
	if(s == screens[0])
		mapwin(s->barwin);
}
Ejemplo n.º 3
0
int
QLuaConsole::Private::getchar()
{
  // --- This runs from the console thread,
  //     mutex is unlocked.

  // is data available already?
  int fd = fileno(stdin);
  if (wait_for_input(1, &fd, false) >= 0)
    return fgetc(stdin);
  // we must wait
  QMutexLocker lock(&mutex);
  while (! killConsole)
    {
      int fds[3];
      int nfd = 0;
      if (! throttleActive)
        fds[nfd++] = stdoutPipe[0];
      fds[nfd++] = commandPipe[0];
      fds[nfd++] = fileno(stdin);
      lock.unlock();
      int fd = wait_for_input(nfd, fds);
      lock.relock();
      if (! throttleActive)
        copyout();
      if (fd == commandPipe[0])
        {
          char c = (char)NoCmd;
          if (::read(commandPipe[0], &c, 1) > 0)
            switch( (enum Command)c )
              {
              case HandlerCmd:
                sethandler();
                break;
              case DrainCmd:
                msleep(10);
                copyout(throttleActive = false);
                drain.wakeAll();
                break;
              case BreakCmd:
                if (lua && breakStopsLua) 
                  lua->stop();
                emit q->ttyBreak();
                break;
              case KillCmd:
                killConsole = true;
              case AbortCmd:
                rtty_status = RttyAbort;
              default:
                break;
              }
        }
      if (rtty_status == RttyAbort)
        break;
      if (fd == fileno(stdin))
        return fgetc(stdin);
    }
  return EOF;
}
Ejemplo n.º 4
0
static bool
destroy_event(Window *w, void *aux, XDestroyWindowEvent *ev) {

	USED(ev);
	sethandler(w, nil);
	event_looprunning = windowmap.nmemb > 0;
	return false;
}
Ejemplo n.º 5
0
/**
 * The main procedure.
 * @param argc The command line.
 * @param argv The number of options in the command line.
 * @retval EXIT_SUCCESS Upon successful termination.
 * @retval EXIT_FAILURE When an error occurs.
 */
int
main(int argc, char **argv) {
	int port, fifo, listener_socket;
	if (argc != 2) {
		usage(argv[0]);
		return EXIT_FAILURE;
	}
	port = atoi(argv[1]);
	if (port <= 0 || port > 65535) {
		usage(argv[0]);
		return EXIT_FAILURE;
	}

	if (mkfifo(FIFO_NAME, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) < 0)
		if (errno != EEXIST) {
			perror("Create fifo:");
			exit(EXIT_FAILURE);
		}
	if ((fifo = TEMP_FAILURE_RETRY(open(FIFO_NAME, O_RDWR))) < 0) {
		perror("Open fifo:");
		exit(EXIT_FAILURE);
	}
	if (sethandler(sigint_handler, SIGINT)) {
		ERR("Setting SIGINT:");
	}
	if (sethandler(sig_update_handler, SIGRTMIN + 11)) {
		ERR("Setting SIGRTMIN+11:");
	}

	listener_socket = bind_inet_socket(port, SOCK_STREAM);
	doServer(listener_socket, fifo);

	if (TEMP_FAILURE_RETRY(close(listener_socket)) < 0) {
		ERR("Close:");
	}
	if (TEMP_FAILURE_RETRY(close(fifo)) < 0) {
		ERR("Close fifo:");
	}
	if (TEMP_FAILURE_RETRY(unlink(FIFO_NAME)) < 0) {
		ERR("Unlink fifo:");
	}
	printf("Server has terminated normally.\n");
	return EXIT_SUCCESS;
}
Ejemplo n.º 6
0
Archivo: mouse.c Proyecto: bartman/wmii
void
destroyconstraintwin(Window *w) {
	Window *w2;

	if(w->aux) {
		w2 = w->aux;
		sethandler(w2, nil);
		destroywindow(w2);
	}
	destroywindow(w);
}
Ejemplo n.º 7
0
void
QLuaConsole::Private::run()
{
  // --- This runs from the console thread.
  // accept signals in this thread.
  set_sigint_handler(SIG_DFL);
  release_signals(&savedSigSet);
  // loop
  while (! killConsole)
    {
      int fds[2];
      int nfd = 0;
      if (! throttleActive)
        fds[nfd++] = stdoutPipe[0];
      fds[nfd++] = commandPipe[0];
      int fd = wait_for_input(nfd, fds);
      mutex.lock();
      if (! throttleActive)
        copyout();
      if (fd == commandPipe[0])
        {
          char c = (char)NoCmd;
          if (::read(commandPipe[0], &c, 1) > 0)
            switch( (enum Command)c )
              {
              case HandlerCmd:
                sethandler();
                break;
              case DrainCmd:
                msleep(10);
                copyout(throttleActive = false);
                drain.wakeAll();
                break;
              case BreakCmd:
                if (lua && breakStopsLua) 
                  lua->stop();
                emit q->ttyBreak();
                break;
              case ReadlineCmd:
                readline();
                break;
              case KillCmd:
                killConsole = true;
              default:
                break;
              }
        }
      pulse.wakeAll();
      mutex.unlock();
    }
  // reset signals
  set_sigint_handler(SIG_DFL);
}
int main(int argc, char** argv) {
    int fd, part_size, file_id;
	int k = 5;
	struct file_info* file_info;
	printf("%10d\n", k);


    sleep(2);

    if(argc!=4) {
		usage(argv[0]);
		return EXIT_FAILURE;
	}

    if(sethandler(SIG_IGN,SIGPIPE)) ERR("Seting SIGPIPE:");
    if(sethandler(sigint_handler,SIGINT)) ERR("Seting SIGINT:");

    fd = connect_socket(argv[1], atoi(argv[2]));

	send_message(fd, "UPL", "");

    part_size = wait_for_system_readiness(fd);

	file_info = get_file_info(fd, argv[3], part_size);

	if(( file_id = send_file_info(fd, argv[3], part_size, file_info)) < 0) ERR("write");

	file_info -> file_id = file_id;
	printf("File ID: %d\n\n\n\\n\n\n\n\n\n\n\\n\n\n\n\n\n\\n\n\n\n\n", file_info -> file_id);
	send_file(fd, argv[3], file_info, part_size);
	printf("File ID: %d\n\n\n\\n\n\n\n\n\n\n\\n\n\n\n\n\n\\n\n\n\n\n", file_info -> file_id);

	if(TEMP_FAILURE_RETRY(close(fd))<0) ERR("close");

	free(file_info);
    return 0;
}
Ejemplo n.º 9
0
int main(int argc, char **argv)
{
    int port, timestep;

    if(argc != 3)
        usage(argv[0]);

    port = atoi(argv[1]);
    timestep = atoi(argv[2]);

    if(port <= 0 || timestep <= 0)
        usage(argv[0]);

    if(sethandler(SIG_IGN, SIGPIPE))
        error_exit("Setting SIGPIPE handler:");
    if(sethandler(sigint_handler, SIGINT))
        error_exit("Setting SIGINT handler:");

    t_sigmask(SIGINT, SIG_BLOCK);

    server_work((uint16_t)port, timestep);

    return EXIT_SUCCESS;
}
Ejemplo n.º 10
0
Archivo: root.c Proyecto: bartman/wmii
void
root_init(void) {
	WinAttr wa;

	wa.event_mask = EnterWindowMask
		      | FocusChangeMask
		      | LeaveWindowMask
		      | PointerMotionMask
		      | SubstructureNotifyMask
		      | SubstructureRedirectMask;
	wa.cursor = cursor[CurNormal];
	setwinattr(&scr.root, &wa,
			  CWEventMask
			| CWCursor);
	sethandler(&scr.root, &handlers);
}
Ejemplo n.º 11
0
int main(int argc, char **argv){
	system("clear");
	fprintf(stdout, "Server start\n");

	//check parameters (Must be: port_number)
	if(argc != 2){
		usage(argv[0]);
	}

	//Init signal process
	//TODO To update
	sigset_t mask, oldmask;
	sethandler(SIG_IGN, SIGPIPE);
	//sethandler(siginthandler, SIGINT);
	sigemptyset(&mask);
	sigaddset(&mask, SIGINT);
	//sigprocmask(SIG_BLOCK, &mask, &oldmask);

	//Create the server socket, bind it, start listening
	int sock = create_server_tcp_socket(atoi(argv[1]), BACKLOG);
	if(sock < 0){
		fprintf(stderr, "Unable to start the server (Unable to create the socket)...\n");
		return EXIT_FAILURE;
	}

	//Initialize server data
	ServerData server;
	server_data_init(&server);
	User *admin = user_create("admin"); //Admin user just for the default room
	server_data_add_room(&server, admin, ROOM_WELCOME_NAME);

	//Start listening for new clients
	server_start_listening_clients(&server, sock);

	//Close the socket
	fprintf(stdout, "Server is closing. Close socket...\n");
	if(TEMP_FAILURE_RETRY(close(sock)) < 0){
		fprintf(stderr, "Error while closing the socket...\n");
		return EXIT_FAILURE;
	}

	fprintf(stdout, "Server is stopped\n");
	return EXIT_SUCCESS;
}
Ejemplo n.º 12
0
Window*
constraintwin(Rectangle r) {
	Window *w;

	w = createwindow(&scr.root, r, 0, InputOnly, nil, 0);
	if(0) {
		Window *w2;

		w2 = createwindow(&scr.root, r, 0, InputOutput, nil, 0);
		selectinput(w2, ExposureMask);
		w->aux = w2;

		setborder(w2, 1, &def.focuscolor.border);
		sethandler(w2, &chandler);
		mapwin(w2);
		raisewin(w2);
	}
	mapwin(w);
	return w;
}
Ejemplo n.º 13
0
/**
 * Main function of a thread.
 * @param thread_args Pointer to a structure containing arguments that are used by the thread.
 */
void
*thread_work(void *thread_args) {
	int i, fdmax;
	fd_set base_rdfs, rdfs;
	pthread_t tid;
	memcpy(&tdata, (thread_data_s*) thread_args, sizeof(thread_data_s));
	global_thread_rdfs = &base_rdfs;
	global_thrad_fdmax = &fdmax;
	tid = pthread_self();
	printf("Thread %d started\n", (int) tid);
	if ((fdmax = prepare_descriptor_set(&base_rdfs)) == -1) {
		fprintf(stderr, "(Thread %d) Unable to prepare descriptor set\n", (int) tid);
		exit(EXIT_FAILURE);
	}
	if (sethandler(sig_handler, SIGRTMIN + 1)) {
		ERR("Setting SIGRTMIN + 1:");
	}
	while (thwork) {
		rdfs = base_rdfs;
		if (pselect(fdmax + 1, &rdfs, NULL, NULL, NULL, NULL) > 0) {
			for (i = 0; i <= fdmax; i++) {
				if (FD_ISSET(i, &rdfs)) {
					thread_communicate(i, &base_rdfs, &tdata);
				}
			}
		} else {
			if (EINTR == errno)
				continue;
			ERR("Thread pselect:");
		}
	}
	pthread_cleanup_push(cleanup_handler, NULL);
	pthread_cleanup_pop(1);
	printf("Thread %d ended\n", (int) tid);
	pthread_exit(NULL);
	return NULL;
}
Ejemplo n.º 14
0
int
main(int argc, char *argv[]) {
	char *s;

	fmtinstall('r', errfmt);
extern int fmtevent(Fmt*);
	fmtinstall('E', fmtevent);

	ARGBEGIN{
	default:
		usage();
	}ARGEND;

	s = EARGF(usage());
	if(!getulong(s, &win.xid))
		usage();

	if(argc)
		usage();

	setlocale(LC_CTYPE, "");

	initdisplay();

	frame = findframe(&win);
	getwinsize(&frame);
	restrut();
	sethandler(&frame, &handlers);
	selectinput(&frame, StructureNotifyMask);

	running = true;
	xevent_loop();

	XCloseDisplay(display);
	return 0;
}
Ejemplo n.º 15
0
static void test_sys32_regs(void (*do_syscall)(struct syscall_args32 *))
{
	struct syscall_args32 args = {
		.nr = 224,	/* gettid */
		.arg0 = 10, .arg1 = 11, .arg2 = 12,
		.arg3 = 13, .arg4 = 14, .arg5 = 15,
	};

	do_syscall(&args);

	if (args.nr != getpid() ||
	    args.arg0 != 10 || args.arg1 != 11 || args.arg2 != 12 ||
	    args.arg3 != 13 || args.arg4 != 14 || args.arg5 != 15) {
		printf("[FAIL]\tgetpid() failed to preseve regs\n");
		nerrs++;
	} else {
		printf("[OK]\tgetpid() preserves regs\n");
	}

	sethandler(SIGUSR1, empty_handler, 0);

	args.nr = 37;	/* kill */
	args.arg0 = getpid();
	args.arg1 = SIGUSR1;
	do_syscall(&args);
	if (args.nr != 0 ||
	    args.arg0 != getpid() || args.arg1 != SIGUSR1 || args.arg2 != 12 ||
	    args.arg3 != 13 || args.arg4 != 14 || args.arg5 != 15) {
		printf("[FAIL]\tkill(getpid(), SIGUSR1) failed to preseve regs\n");
		nerrs++;
	} else {
		printf("[OK]\tkill(getpid(), SIGUSR1) preserves regs\n");
	}
	clearhandler(SIGUSR1);
}

static void test_ptrace_syscall_restart(void)
{
	printf("[RUN]\tptrace-induced syscall restart\n");
	pid_t chld = fork();
	if (chld < 0)
		err(1, "fork");

	if (chld == 0) {
		if (ptrace(PTRACE_TRACEME, 0, 0, 0) != 0)
			err(1, "PTRACE_TRACEME");

		printf("\tChild will make one syscall\n");
		raise(SIGSTOP);

		syscall(SYS_gettid, 10, 11, 12, 13, 14, 15);
		_exit(0);
	}

	int status;

	/* Wait for SIGSTOP. */
	if (waitpid(chld, &status, 0) != chld || !WIFSTOPPED(status))
		err(1, "waitpid");

	struct user_regs_struct regs;

	printf("[RUN]\tSYSEMU\n");
	if (ptrace(PTRACE_SYSEMU, chld, 0, 0) != 0)
		err(1, "PTRACE_SYSCALL");
	wait_trap(chld);

	if (ptrace(PTRACE_GETREGS, chld, 0, &regs) != 0)
		err(1, "PTRACE_GETREGS");

	if (regs.user_syscall_nr != SYS_gettid ||
	    regs.user_arg0 != 10 || regs.user_arg1 != 11 ||
	    regs.user_arg2 != 12 || regs.user_arg3 != 13 ||
	    regs.user_arg4 != 14 || regs.user_arg5 != 15) {
		printf("[FAIL]\tInitial args are wrong (nr=%lu, args=%lu %lu %lu %lu %lu %lu)\n", (unsigned long)regs.user_syscall_nr, (unsigned long)regs.user_arg0, (unsigned long)regs.user_arg1, (unsigned long)regs.user_arg2, (unsigned long)regs.user_arg3, (unsigned long)regs.user_arg4, (unsigned long)regs.user_arg5);
		nerrs++;
	} else {
		printf("[OK]\tInitial nr and args are correct\n");
	}

	printf("[RUN]\tRestart the syscall (ip = 0x%lx)\n",
	       (unsigned long)regs.user_ip);

	/*
	 * This does exactly what it appears to do if syscall is int80 or
	 * SYSCALL64.  For SYSCALL32 or SYSENTER, though, this is highly
	 * magical.  It needs to work so that ptrace and syscall restart
	 * work as expected.
	 */
	regs.user_ax = regs.user_syscall_nr;
	regs.user_ip -= 2;
	if (ptrace(PTRACE_SETREGS, chld, 0, &regs) != 0)
		err(1, "PTRACE_SETREGS");

	if (ptrace(PTRACE_SYSEMU, chld, 0, 0) != 0)
		err(1, "PTRACE_SYSCALL");
	wait_trap(chld);

	if (ptrace(PTRACE_GETREGS, chld, 0, &regs) != 0)
		err(1, "PTRACE_GETREGS");

	if (regs.user_syscall_nr != SYS_gettid ||
	    regs.user_arg0 != 10 || regs.user_arg1 != 11 ||
	    regs.user_arg2 != 12 || regs.user_arg3 != 13 ||
	    regs.user_arg4 != 14 || regs.user_arg5 != 15) {
		printf("[FAIL]\tRestart nr or args are wrong (nr=%lu, args=%lu %lu %lu %lu %lu %lu)\n", (unsigned long)regs.user_syscall_nr, (unsigned long)regs.user_arg0, (unsigned long)regs.user_arg1, (unsigned long)regs.user_arg2, (unsigned long)regs.user_arg3, (unsigned long)regs.user_arg4, (unsigned long)regs.user_arg5);
		nerrs++;
	} else {
		printf("[OK]\tRestarted nr and args are correct\n");
	}

	printf("[RUN]\tChange nr and args and restart the syscall (ip = 0x%lx)\n",
	       (unsigned long)regs.user_ip);

	regs.user_ax = SYS_getpid;
	regs.user_arg0 = 20;
	regs.user_arg1 = 21;
	regs.user_arg2 = 22;
	regs.user_arg3 = 23;
	regs.user_arg4 = 24;
	regs.user_arg5 = 25;
	regs.user_ip -= 2;

	if (ptrace(PTRACE_SETREGS, chld, 0, &regs) != 0)
		err(1, "PTRACE_SETREGS");

	if (ptrace(PTRACE_SYSEMU, chld, 0, 0) != 0)
		err(1, "PTRACE_SYSCALL");
	wait_trap(chld);

	if (ptrace(PTRACE_GETREGS, chld, 0, &regs) != 0)
		err(1, "PTRACE_GETREGS");

	if (regs.user_syscall_nr != SYS_getpid ||
	    regs.user_arg0 != 20 || regs.user_arg1 != 21 || regs.user_arg2 != 22 ||
	    regs.user_arg3 != 23 || regs.user_arg4 != 24 || regs.user_arg5 != 25) {
		printf("[FAIL]\tRestart nr or args are wrong (nr=%lu, args=%lu %lu %lu %lu %lu %lu)\n", (unsigned long)regs.user_syscall_nr, (unsigned long)regs.user_arg0, (unsigned long)regs.user_arg1, (unsigned long)regs.user_arg2, (unsigned long)regs.user_arg3, (unsigned long)regs.user_arg4, (unsigned long)regs.user_arg5);
		nerrs++;
	} else {
		printf("[OK]\tReplacement nr and args are correct\n");
	}

	if (ptrace(PTRACE_CONT, chld, 0, 0) != 0)
		err(1, "PTRACE_CONT");
	if (waitpid(chld, &status, 0) != chld)
		err(1, "waitpid");
	if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
		printf("[FAIL]\tChild failed\n");
		nerrs++;
	} else {
		printf("[OK]\tChild exited cleanly\n");
	}
}
Ejemplo n.º 16
0
int main(void) {
    char decission[50];
    int s, sem;
    packet* rec = malloc(sizeof (packet));
    if(rec == NULL){
        ERR("malloc");
    }
    packet* tmp = malloc(sizeof (packet));
    if(tmp == NULL){
        ERR("malloc");
    }
    char c;
    int x, y, points,i;
    int isAnyTileAvaliable;
    semaphore_init(&sem, 'E', 1);
    
    /* Set signals handlers */
	if(sethandler(sigint_handler,SIGINT)) ERR("Setting SIGINT:");
	if(sethandler(sigterm_handler,SIGTERM)) ERR("Setting SIGTERM:");

    /*********  TCP IP  *********/
    s = tcp_connect_socket("localhost", 2000);

    printf("##############################\n");
    printf("## WELCOME TO SCRABBLE GAME ##\n");
    printf("##############################\n");


    while (g_doWork) {
        int t;

        if ((t = tcp_socket_read_packet(s, rec)) == 0 && g_doWork==1) {
            perror("Server closed connection client\n");
            break;
        } else if (t < 0) {
            perror("recv");
            break;
        }
        switch (rec->msg) {
            case NO_PLAYER:
                printf("Waiting for another player to connect...\n");
                break;
            case PAIR_MATCH:
                printf("Player found - starting the game...\n");
                break;
            case INFO:
                printf("Player found - starting the game...\n");
                scrabble_game_print_title();
                scrabble_game_print_board(rec->currentBoard);
                scrabble_game_print_wait_for_move();
                break;
            case REQUEST_MOVE:
                /* Print points in the right order */
                scrabble_game_print_title();
                scrabble_game_print_points(rec->p1Points, rec->p2Points, rec->playerType);

                /* Print current board state */
                scrabble_game_print_board(rec->currentBoard);

                /* Print available tiles */
                printf("----------------------------------------\n              ");
                scrabble_game_print_available_tiles(rec->tiles, 5);
                printf("----------------------------------------\n");
                isAnyTileAvaliable = 0;
                for(i=0; i<5;i++){
                    if(rec->tiles[i] != 'x'){
                        isAnyTileAvaliable = 1;
                    }
                }
                if(isAnyTileAvaliable == 1) {
                    points = 0;
                    if(-1 == gather_input(&c, &x, &y, &points, rec->tiles, rec->currentBoard)) {
                        printf("gater input error\n");
                    }else {
                        /* Print updated points */
                        scrabble_game_print_title();
                        if (rec->playerType == FIRST) rec->p1Points += points;
                        if (rec->playerType == SECOND) rec->p2Points += points;
                        scrabble_game_print_points(rec->p1Points, rec->p2Points, rec->playerType);

                        /* Print updated board */
                        rec->currentBoard[x][y] = c;
                        scrabble_game_print_board(rec->currentBoard);

                        /* Send data to server. */
                        tmp->msg = MOVE_DATA;
                        tmp->letter = c;
                        tmp->x_coord = x;
                        tmp->y_coord = y;
                        tmp->p1Points = rec->p1Points;
                        tmp->p2Points = rec->p2Points;
                        tcp_socket_send_packet(s, tmp);
                        scrabble_game_print_wait_for_move();
                    }
                }
                else{
                    printf("##########################################\n");
                    printf("##             END OF MATCH             ##\n");
                    printf("##########################################\n");
                    printf("Do you want to play another game?(Y/N)\n");
                    scanf(" %c", decission);
                    printf("%s \n",decission);
                    tmp->isMatchOngoing = -1;
                    if (decission[0] == 'Y') {
                        tmp->msg = PLAY_ANOTHER_GAME;
                        tcp_socket_send_packet(s, tmp);
                    }
                    else
                    {
                        tmp->msg = FINISH_GAME;
                        printf("isMatchOngoing = %d \n", tmp->isMatchOngoing);
                        tcp_socket_send_packet(s, tmp);
                        return EXIT_SUCCESS;
                    }
                }
                break;
            case DISCONNECTED:

                printf("##########################################\n");
                printf("##            Connection lost!          ##\n");
                printf("##########################################\n");
                printf("Sorry but connection with other player is\n");
                printf("lost. Do you want to play another game?(Y/N)\n");
                scanf(" %c", decission);
                printf("%s \n",decission);
                if (decission[0] == 'Y') {
                    tmp->msg = PLAY_ANOTHER_GAME;
                    tcp_socket_send_packet(s, tmp);
                } 
                else 
                {
                    tmp->msg = FINISH_GAME;
                    tcp_socket_send_packet(s, tmp);
                    return EXIT_SUCCESS;
                }
                break;
                
            case EXIT:
                printf("Server disconnected.\n");
                return EXIT_SUCCESS;
            default:
                printf("Cannot interpret packet's message: %d \n", rec->msg);
        }
    };
    printf("Disconnected\n");
    if(-1 == close(s)){
        ERR("close");
    }
    return 0;
}
Ejemplo n.º 17
0
// Register signal handlers for all defined signals that typicall result
// in process termination.
int init_signal_handlers()
{
  int result = 0;
/* Don't trap these.  It is unlikely that a test would ever generate such 
   a signal on its own and trapping them interfers with a user's ability 
   to stop a test.  SIGHUP implies that the controlling terminal was closed.  
   If the user does ctrl-C or ctrl-\ (SIGINT and SIGQUIT, respectively) and
   we trap these then just the current test stops.  If we leave the default
   behavior for them then the whole test suite stops.  The latter is likely 
   the desired behavior.  SIGTERM is the default signal sent by the 'kill'
   command.
#ifdef SIGHUP
  result += sethandler( SIGHUP );
#endif
#ifdef SIGINT
  result += sethandler( SIGINT );
#endif
#ifdef SIGQUIT
  result += sethandler( SIGQUIT );
#endif
#ifdef SIGTERM
  result += sethandler( SIGTERM );
#endif
*/

#ifdef SIGILL
  result += sethandler( SIGILL );
#endif
#ifdef SIGTRAP
  result += sethandler( SIGTRAP );
#endif
#ifdef SIGABRT
  result += sethandler( SIGABRT );
#endif
#ifdef SIGBUS
  result += sethandler( SIGBUS );
#endif
#ifdef SIGFPE
  result += sethandler( SIGFPE );
#endif
#ifdef SIGSEGV
  result += sethandler( SIGSEGV );
#endif

/* Catching these causes problems with mpich2 1.3.1p1 and a
   test should never receive such a signal anyway.
#ifdef SIGUSR1
  result += sethandler( SIGUSR1 );
#endif
#ifdef SIGUSR2
  result += sethandler( SIGUSR2 );
#endif
*/

/* Don't trap SIGCHLD.  The only way a test should receive
   such a signal is if it actually forked a child process.
   That is unlikely, but if it does happen the test probably
   wants to handle the signal itself.
#ifdef SIGCHLD
  result += sethandler( SIGCHLD );
#endif
*/

#ifdef SIGPIPE
  result += sethandler( SIGPIPE );
#endif
#ifdef SIGIO
  result += sethandler( SIGIO );
#endif
#ifdef SIGSYS
  result += sethandler( SIGSYS );
#endif
  return result;
}
Ejemplo n.º 18
0
int
main(int argc, char **argv)
{
	const char *av = NULL;
	int func_total, file_total;
        char arg_dbpath[MAXPATHLEN];
	const char *index = NULL;
	int optchar;
        int option_index = 0;
	STATISTICS_TIME *tim;

	arg_dbpath[0] = 0;
	basic_check();
	/*
	 * Setup GTAGSCONF and GTAGSLABEL environment variable
	 * according to the --gtagsconf and --gtagslabel option.
	 */
	preparse_options(argc, argv);
	/*
	 * Load configuration values.
	 */
	if (!vgetcwd(cwdpath, sizeof(cwdpath)))
		die("cannot get current directory.");
	openconf(cwdpath);
	configuration();
	/*
	 * setup_langmap() is needed to use decide_lang().
	 */
	setup_langmap(langmap);
	save_environment(argc, argv);
	/*
	 * insert htags_options at the head of argv.
	 */
	setenv_from_config();
	{
		char *env = getenv("HTAGS_OPTIONS");
		if (env && *env)
			argv = prepend_options(&argc, argv, env);
	}
	while ((optchar = getopt_long(argc, argv, "acd:DfFghIm:nNoqst:Tvwx", long_options, &option_index)) != EOF) {
		switch (optchar) {
		case 0:
			/* already flags set */
			break;
		case OPT_AUTO_COMPLETION:
			auto_completion = 1;
			if (optarg) {
				if (atoi(optarg) > 0)
					auto_completion_limit = optarg;
				else
					die("The option value of --auto-completion must be numeric.");
			}
			break;
		case OPT_CFLOW:
			call_file = optarg;
			break;
		case OPT_CALL_TREE:
			call_file = optarg;
			break;
		case OPT_CALLEE_TREE:
			callee_file = optarg;
			break;
		case OPT_CVSWEB:
			cvsweb_url = optarg;
			break;
		case OPT_CVSWEB_CVSROOT:
			cvsweb_cvsroot = optarg;
			break;
		case OPT_GTAGSCONF:
		case OPT_GTAGSLABEL:
			/* These options are already parsed in preparse_options() */
			break;
		case OPT_INSERT_FOOTER:
			insert_footer = optarg;
			break;
		case OPT_INSERT_HEADER:
			insert_header = optarg;
			break;
		case OPT_HTML_HEADER:
			{
				STATIC_STRBUF(sb);
				if (!test("r", optarg))
					die("file '%s' not found.", optarg);
				strbuf_clear(sb);
				loadfile(optarg, sb);
				html_header = strbuf_value(sb);
			}
			break;
		case OPT_ITEM_ORDER:
			item_order = optarg;
			break;
		case OPT_TABS:
			if (atoi(optarg) > 0)
				tabs = atoi(optarg);
			else
				die("--tabs option requires numeric value.");
                        break;
		case OPT_NCOL:
			if (atoi(optarg) > 0)
				ncol = atoi(optarg);
			else
				die("--ncol option requires numeric value.");
                        break;
		case OPT_TREE_VIEW:
			tree_view = 1;
			if (optarg)
				tree_view_type = optarg;
			break;
                case 'a':
                        aflag++;
                        break;
                case 'd':
			strlimcpy(arg_dbpath, optarg, sizeof(arg_dbpath));
                        break;
                case 'D':
			dynamic = 1;
                        break;
                case 'f':
                        fflag++;
                        break;
                case 'F':
                        Fflag++;
                        break;
                case 'g':
                        gflag++;
                        break;
                case 'h':
			definition_header = AFTER_HEADER;
			if (optarg) {
				if (!strcmp(optarg, "before"))
					definition_header = BEFORE_HEADER;
				else if (!strcmp(optarg, "right"))
					definition_header = RIGHT_HEADER;
				else if (!strcmp(optarg, "after"))
					definition_header = AFTER_HEADER;
				else
					die("The option value of --func-header must be one of 'before', 'right' and 'after'.");
			}
                        break;
                case 'I':
                        Iflag++;
                        break;
                case 'm':
			main_func = optarg;
                        break;
                case 'n':
                        nflag++;
			if (optarg) {
				if (atoi(optarg) > 0)
					ncol = atoi(optarg);
				else
					die("The option value of --line-number must be numeric.");
			}
                        break;
                case 'o':
			other_files = 1;
                        break;
                case 's':
			symbol = 1;
                        break;
                case 'T':
			table_flist = 1;
			if (optarg) {
				if (atoi(optarg) > 0)
					flist_fields = atoi(optarg);
				else
					die("The option value of the --table-flist must be numeric.");
			}
                        break;
                case 't':
			title = optarg;
                        break;
                case 'q':
                        qflag++;
			setquiet();
                        break;
                case 'v':
                        vflag++;
			setverbose();
                        break;
                case 'w':
                        wflag++;
                        break;
                default:
                        usage();
                        break;
		}
	}
	/*
	 * Leaving everything to htags.
	 * Htags selects popular options for you.
	 */
	if (suggest2)
		suggest = 1;
	if (suggest) {
		int gtags_not_found = 0;
		char dbpath[MAXPATHLEN];

		aflag = Iflag = nflag = vflag = 1;
		setverbose();
		definition_header = AFTER_HEADER;
		other_files = symbol = show_position = table_flist = fixed_guide = 1;
		if (arg_dbpath[0]) {
			if (!test("f", makepath(arg_dbpath, dbname(GTAGS), NULL)))
				gtags_not_found = 1;
		} else if (gtagsexist(".", dbpath, sizeof(dbpath), 0) == 0) {
			gtags_not_found = 1;
		}
		if (gtags_not_found)
			gflag = 1;
	}
	if (suggest2) {
		Fflag = 1;				/* uses frame */
		fflag = dynamic = 1;			/* needs a HTTP server */
		auto_completion = tree_view = 1;	/* needs javascript */
	}
	if (call_file && !test("fr", call_file))
		die("cflow file not found. '%s'", call_file);
	if (callee_file && !test("fr", callee_file))
		die("cflow file not found. '%s'", callee_file);
	if (insert_header && !test("fr", insert_header))
		die("page header file '%s' not found.", insert_header);
	if (insert_footer && !test("fr", insert_footer))
		die("page footer file '%s' not found.", insert_footer);
	if (!fflag)
		auto_completion = 0;
        argc -= optind;
        argv += optind;
        if (!av)
                av = (argc > 0) ? *argv : NULL;

	if (debug)
		setdebug();
	settabs(tabs);					/* setup tab skip */
        if (qflag) {
                setquiet();
		vflag = 0;
	}
        if (show_version)
                version(av, vflag);
        if (show_help)
                help();
	/*
	 * Invokes gtags beforehand.
	 */
	if (gflag) {
		STRBUF *sb = strbuf_open(0);

		strbuf_puts(sb, gtags_path);
		if (vflag)
			strbuf_puts(sb, " -v");
		if (wflag)
			strbuf_puts(sb, " -w");
		if (suggest2 && enable_idutils && usable("mkid"))
			strbuf_puts(sb, " -I");
		if (arg_dbpath[0]) {
			strbuf_putc(sb, ' ');
			strbuf_puts(sb, arg_dbpath);
		}
		if (system(strbuf_value(sb)))
			die("cannot execute gtags(1) command.");
		strbuf_close(sb);
	}
	/*
	 * get dbpath.
	 */
	if (arg_dbpath[0]) {
		strlimcpy(dbpath, arg_dbpath, sizeof(dbpath));
	} else {
		int status = setupdbpath(0);
		if (status < 0)
			die_with_code(-status, "%s", gtags_dbpath_error);
		strlimcpy(dbpath, get_dbpath(), sizeof(dbpath));
	}
	if (!title) {
		char *p = strrchr(cwdpath, sep);
		title = p ? p + 1 : cwdpath;
	}
	if (cvsweb_url && test("d", "CVS"))
		use_cvs_module = 1;
	/*
	 * decide directory in which we make hypertext.
	 */
	if (av) {
		char realpath[MAXPATHLEN];

		if (!test("dw", av))
			die("'%s' is not writable directory.", av);
		if (chdir(av) < 0)
			die("directory '%s' not found.", av);
		if (!vgetcwd(realpath, sizeof(realpath)))
			die("cannot get current directory");
		if (chdir(cwdpath) < 0)
			die("cannot return to original directory.");
		snprintf(distpath, sizeof(distpath), "%s/HTML", realpath);
	} else {
		snprintf(distpath, sizeof(distpath), "%s/HTML", cwdpath);
	}
	/*
	 * Existence check of tag files.
	 */
	{
		int i;
		const char *path;
		GTOP *gtop;

		for (i = GPATH; i < GTAGLIM; i++) {
			path = makepath(dbpath, dbname(i), NULL);
			gtags_exist[i] = test("fr", path);
		}
		/*
		 * Real GRTAGS includes virtual GSYMS.
		 */
		gtags_exist[GSYMS] = symbol ? 1 : 0;
		if (!gtags_exist[GPATH] || !gtags_exist[GTAGS] || !gtags_exist[GRTAGS])
			die("GPATH, GTAGS and/or GRTAGS not found. Please reexecute htags with the -g option.");
		/*
		 * version check.
		 * Do nothing, but the version of tag file will be checked.
		 */
		gtop = gtags_open(dbpath, cwdpath, GTAGS, GTAGS_READ, 0);
		gtags_close(gtop);
		/*
		 * Check whether GRTAGS is empty.
		 */
		gtop = gtags_open(dbpath, cwdpath, GRTAGS, GTAGS_READ, 0);
		if (gtags_first(gtop, NULL, 0) == NULL)
			grtags_is_empty = 1;
		gtags_close(gtop);
	}
	/*
	 * make dbpath absolute.
	 */
	{
		char buf[MAXPATHLEN];
		if (realpath(dbpath, buf) == NULL)
			die("cannot get realpath of dbpath.");
		strlimcpy(dbpath, buf, sizeof(dbpath));
	}
	/*
	 * The older version (4.8.7 or former) of GPATH doesn't have files
         * other than source file. The oflag requires new version of GPATH.
	 */
	if (other_files) {
		GFIND *gp = gfind_open(dbpath, NULL, 0, 0);
		if (gp->version < 2)
			die("GPATH is old format. Please remake it by invoking gtags(1).");
		gfind_close(gp);
	}
	/*
	 * for global(1) and gtags(1).
	 */
	set_env("GTAGSROOT", cwdpath);
	set_env("GTAGSDBPATH", dbpath);
	set_env("GTAGSLIBPATH", "");
	/*------------------------------------------------------------------
	 * MAKE FILES
	 *------------------------------------------------------------------
	 *       HTML/cgi-bin/global.cgi ... CGI program (1)
	 *       HTML/cgi-bin/ghtml.cgi  ... unzip script (1)
	 *       HTML/.htaccess          ... skeleton of .htaccess (1)
	 *       HTML/help.html          ... help file (2)
	 *       HTML/R/                 ... references (3)
	 *       HTML/D/                 ... definitions (3)
	 *       HTML/search.html        ... search index (4)
	 *       HTML/defines.html       ... definitions index (5)
	 *       HTML/defines/           ... definitions index (5)
	 *       HTML/files/             ... file index (6)
	 *       HTML/index.html         ... index file (7)
	 *       HTML/mains.html         ... main index (8)
	 *       HTML/null.html          ... main null html (8)
	 *       HTML/S/                 ... source files (9)
	 *       HTML/I/                 ... include file index (9)
	 *       HTML/rebuild.sh         ... rebuild script (10)
	 *       HTML/style.css          ... style sheet (11)
	 *------------------------------------------------------------------
	 */
	/* for clean up */
	signal_setup();
	sethandler(clean);

        HTML = normal_suffix;

	message("[%s] Htags started", now());
	init_statistics();
	/*
	 * (#) check if GTAGS, GRTAGS is the latest.
	 */
	if (get_dbpath())
		message(" Using %s/GTAGS.", get_dbpath());
	if (grtags_is_empty)
		message(" GRTAGS is empty.");
	if (gpath_open(dbpath, 0) < 0)
		die("GPATH not found.");
	if (!w32) {
		/* UNDER CONSTRUCTION */
	}
	if (auto_completion || tree_view) {
		STATIC_STRBUF(sb);
		strbuf_clear(sb);
		strbuf_puts_nl(sb, "<script type='text/javascript' src='js/jquery.js'></script>");
		if (auto_completion)
			loadfile(makepath(datadir, "gtags/jscode_suggest", NULL), sb);
		if (tree_view)
			loadfile(makepath(datadir, "gtags/jscode_treeview", NULL), sb);
		jscode = strbuf_value(sb);
	}
	/*
	 * (0) make directories
	 */
	message("[%s] (0) making directories ...", now());
	if (!test("d", distpath))
		if (mkdir(distpath, 0777) < 0)
			die("cannot make directory '%s'.", distpath);
	make_directory_in_distpath("files");
	make_directory_in_distpath("defines");
	make_directory_in_distpath(SRCS);
	make_directory_in_distpath(INCS);
	make_directory_in_distpath(INCREFS);
	if (!dynamic) {
		make_directory_in_distpath(DEFS);
		make_directory_in_distpath(REFS);
		if (symbol)
			make_directory_in_distpath(SYMS);
	}
	if (fflag || dynamic)
		make_directory_in_distpath("cgi-bin");
	if (Iflag)
		make_directory_in_distpath("icons");
	if (auto_completion || tree_view)
		 make_directory_in_distpath("js");
	/*
	 * (1) make CGI program
	 */
	if (fflag || dynamic) {
		char cgidir[MAXPATHLEN];

		snprintf(cgidir, sizeof(cgidir), "%s/cgi-bin", distpath);
		message("[%s] (1) making CGI program ...", now());
		if (fflag || dynamic)
			makeprogram(cgidir, "global.cgi", 0755);
		if (auto_completion)
			makeprogram(cgidir, "completion.cgi", 0755);
		makehtaccess(cgidir, ".htaccess", 0644);
	} else {
		message("[%s] (1) making CGI program ...(skipped)", now());
	}
	if (av) {
		const char *path = makepath(distpath, "GTAGSROOT", NULL);
		FILE *op = fopen(path, "w");
		if (op == NULL)
			die("cannot make file '%s'.", path);
		fputs(cwdpath, op);
		fputc('\n', op);
		fclose(op);
	}
	/*
	 * (2) make help file
	 */
	message("[%s] (2) making help.html ...", now());
	makehelp("help.html");
	/*
	 * (#) load GPATH
	 */
	load_gpath(dbpath);

	/*
	 * (3) make function entries (D/ and R/)
	 *     MAKING TAG CACHE
	 */
	message("[%s] (3) making tag lists ...", now());
	cache_open();
	tim = statistics_time_start("Time of making tag lists");
	func_total = makedupindex();
	statistics_time_end(tim);
	message("Total %d functions.", func_total);
	/*
	 * (4) search index. (search.html)
	 */
	if (Fflag && fflag) {
		message("[%s] (4) making search index ...", now());
		makesearchindex("search.html");
	}
	{
		STRBUF *defines = strbuf_open(0);
		STRBUF *files = strbuf_open(0);

		/*
		 * (5) make definition index (defines.html and defines/)
		 *     PRODUCE @defines
		 */
		message("[%s] (5) making definition index ...", now());
		tim = statistics_time_start("Time of making definition index");
		func_total = makedefineindex("defines.html", func_total, defines);
		statistics_time_end(tim);
		message("Total %d functions.", func_total);
		/*
		 * (6) make file index (files.html and files/)
		 *     PRODUCE @files, %includes
		 */
		message("[%s] (6) making file index ...", now());
		init_inc();
		tim = statistics_time_start("Time of making file index");
		file_total = makefileindex("files.html", files);
		statistics_time_end(tim);
		message("Total %d files.", file_total);
		html_count += file_total;
		/*
		 * (7) make call tree using cflow(1)'s output (cflow.html)
		 */
		if (call_file || callee_file) {
			message("[%s] (7) making cflow index ...", now());
			tim = statistics_time_start("Time of making cflow index");
			if (call_file)
				if (makecflowindex("call.html", call_file) < 0)
					call_file = NULL;
			if (callee_file)
				if (makecflowindex("callee.html", callee_file) < 0)
					callee_file = NULL;
			statistics_time_end(tim);
		}
		/*
		 * [#] make include file index.
		 */
		message("[%s] (#) making include file index ...", now());
		tim = statistics_time_start("Time of making include file index");
		makeincludeindex();
		statistics_time_end(tim);
		/*
		 * [#] make a common part for mains.html and index.html
		 *     USING @defines @files
		 */
		message("[%s] (#) making a common part ...", now());
		index = makecommonpart(title, strbuf_value(defines), strbuf_value(files));

		strbuf_close(defines);
		strbuf_close(files);
	}
	/*
	 * (7)make index file (index.html)
	 */
	message("[%s] (7) making index file ...", now());
	makeindex("index.html", title, index);
	/*
	 * (8) make main index (mains.html)
	 */
	message("[%s] (8) making main index ...", now());
	makemainindex("mains.html", index);
	/*
	 * (9) make HTML files (SRCS/)
	 *     USING TAG CACHE, %includes and anchor database.
	 */
	message("[%s] (9) making hypertext from source code ...", now());
	tim = statistics_time_start("Time of making hypertext");
	makehtml(file_total);
	statistics_time_end(tim);
	/*
	 * (10) rebuild script. (rebuild.sh)
	 *
	 * Don't grant execute permission to rebuild script.
	 */
	makerebuild("rebuild.sh");
	if (chmod(makepath(distpath, "rebuild.sh", NULL), 0640) < 0)
		die("cannot chmod rebuild script.");
	/*
	 * (11) style sheet file (style.css)
	 */
	if (enable_xhtml) {
		char src[MAXPATHLEN];
		char dist[MAXPATHLEN];
		snprintf(src, sizeof(src), "%s/gtags/style.css", datadir);
		snprintf(dist, sizeof(dist), "%s/style.css", distpath);
		copyfile(src, dist);
	}
	if (auto_completion || tree_view) {
		char src[MAXPATHLEN];
		char dist[MAXPATHLEN];

		snprintf(src, sizeof(src), "%s/gtags/jquery", datadir);
		snprintf(dist, sizeof(dist), "%s/js", distpath);
		copydirectory(src, dist);
		snprintf(src, sizeof(src), "%s/gtags/jquery/images", datadir);
		snprintf(dist, sizeof(dist), "%s/js/images", distpath);
		copydirectory(src, dist);
	}
	message("[%s] Done.", now());
	if (vflag && (fflag || dynamic || auto_completion)) {
		message("\n[Information]\n");
		message(" o Htags was invoked with the -f, -c, -D or --auto-completion option. You should");
		message("   start http server so that cgi-bin/*.cgi is executed as a CGI script.");
 		message("\n If you are using Apache, 'HTML/.htaccess' might be helpful for you.\n");
		message(" Good luck!\n");
	}
	if (Iflag) {
		char src[MAXPATHLEN];
		char dist[MAXPATHLEN];

		snprintf(src, sizeof(src), "%s/gtags/icons", datadir);
		snprintf(dist, sizeof(dist), "%s/icons", distpath);
		copydirectory(src, dist);
	}
	gpath_close();
	/*
	 * Print statistics information.
	 */
	print_statistics(statistics);
	clean();
	return 0;
}