Ejemplo n.º 1
0
int create_server_sock(int port) {
    int addrlen, s, on = 1, x;
    struct sockaddr_in client_addr;

    s = socket(AF_INET, SOCK_STREAM, 0);
    if (s < 0) {
        perror("socket");
        do_cleanup();
        exit(1);
    }

    addrlen = sizeof(client_addr);
    memset(&client_addr, '\0', addrlen);
    client_addr.sin_family = AF_INET;
    client_addr.sin_addr.s_addr = INADDR_ANY;
    client_addr.sin_port = htons(port);
    setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, 4);
    x = bind(s, (struct sockaddr*)&client_addr, addrlen);
    if (x < 0) {
        perror("bind");
        do_cleanup();
        exit(1);
    }

    x = listen(s, 5);
    if (x < 0) {
        perror("listen");
        do_cleanup();
        exit(1);
    }

    return s;
}
Ejemplo n.º 2
0
/*
 * Signal handler.
 *
 * This thread is reponsible for allowing switches between the
 * silent and verbose ttys, and for cleanup tasks after reception
 * of SIGTERM.
 */
void* thf_sighandler(void *unusued)
{
	sigset_t sigset, sigset_switch;
	int sig;

	/* We don't handle SIGALRM. */
	sigemptyset(&sigset);
	sigaddset(&sigset, SIGALRM);
	pthread_sigmask(SIG_BLOCK, &sigset, NULL);

	sigemptyset(&sigset);
	sigaddset(&sigset, SIGUSR1);
	sigaddset(&sigset, SIGUSR2);
	sigaddset(&sigset, SIGTERM);
	sigaddset(&sigset, SIGINT);

	sigemptyset(&sigset_switch);
	sigaddset(&sigset_switch, SIGUSR1);
	sigaddset(&sigset_switch, SIGUSR2);

	while (1) {
		sigwait(&sigset, &sig);

		process_switch_sig(sig);

		/* Internally generated terminate signal */
		if (sig == SIGINT) {
			struct timespec timeout;
			timeout.tv_sec = 0;
			timeout.tv_nsec = 0;
			bool pending = true;

			/*
			 * Process any remaining signals.  There are no guarantees as to the
			 * order in which the signals are delivered, so we have to make sure
			 * all pending signals are processed before exiting.
			 */
			while (pending) {
				sig = sigtimedwait(&sigset_switch, NULL, &timeout);

				if (sig == -1) {
					/* No more pending signals. */
					if (errno == EAGAIN)
						pending = false;
				} else {
					process_switch_sig(sig);
				}
			}

			do_cleanup();
			pthread_exit(NULL);
		} else if (sig == SIGTERM) {
			do_cleanup();
			exit(0);
		}
	}
}
Ejemplo n.º 3
0
void cb_ProcessEventToIC(VLServer server, VLEvent *ev, void * clientData) {

	char *dataPtr;
	DMbuffer dmbuf;
	int dataBytes;

	int *data = (int *)clientData ;


	switch (ev->reason) {
		case VLTransferComplete:
			printf("CBTO %s\n", vlEventToName(ev->reason));
			if (vlDMBufferGetValid(cstate.server, cstate.pathin, 
						cstate.memdrn, &dmbuf) == VLSuccess) {
				dataBytes = dmBufferGetSize(dmbuf);
				printf("VLTransferComplete: %d\n", dataBytes);

				/*
				if (dmICSend(cstate.ic, dmbuf, 0, NULL)
						!= DM_SUCCESS) {
					fprintf(stderr, "failed to send to IC\n");
					do_cleanup();
				} else {
					fprintf(stderr, ">> IC %d\n", dataBytes);
				}
				*/
				dmBufferFree(dmbuf);
			} else {
				fprintf(stderr, "VLTransferComplete: but vlDMBufferGetValid: %s\n", 
						vlStrError(vlGetErrno()));
			}
		break;
		case VLStreamStopped:
			printf("all stop\n");
			do_cleanup() ;
		break;
		case VLSequenceLost:
			printf("Aiiieee - seq lost\n");
			do_cleanup() ;
		break;
		default:
		break;
	}

	if (dmICReceive(cstate.ic, &dmbuf) == DM_SUCCESS) {
		dataBytes = dmBufferGetSize(dmbuf);
		fprintf(stderr, "<< IC %d\n", dataBytes);
		dmBufferFree(dmbuf);
	} else {
		fprintf(stderr, "dmICReceive: no data\n");
	}

	reportStatistics();
}
Ejemplo n.º 4
0
void tst_run_tcases(int argc, char *argv[], struct tst_test *self)
{
	unsigned int i = 0;
	unsigned long long stop_time = 0;
	int cont = 1;

	tst_test = self;
	TCID = tst_test->tid;

	do_setup(argc, argv);

	if (duration > 0)
		stop_time = get_time_ms() + (unsigned long long)(duration * 1000);

	for (;;) {
		cont = 0;

		if (i < (unsigned int)iterations) {
			i++;
			cont = 1;
		}

		if (stop_time && get_time_ms() < stop_time)
			cont = 1;

		if (!cont)
			break;

		run_tests();
	}

	do_cleanup();
	do_exit();
}
Ejemplo n.º 5
0
/*
 * Delay for either a timed period or the wait on the read_fifo
 */
static void delay(unsigned long milli)
{
	char tmp_stg[PERIODIC_MAX_STRLEN];
	int done;
	int ret;

	if (use_fifo) {
		do {
			done = true;
			ret = fscanf(tReadFifo, "%s", tmp_stg);
			if (ret == 0)
				return;
			/*
			 * Look for a command request, and if we get a command
			 * Need to process and then wait again w/o sending data.
			 */
			if (strncmp(tmp_stg, "PID", strnlen(tmp_stg,
				PERIODIC_MAX_STRLEN)) == 0) {
				fprintf(fd_out, " %u\n", getpid());
				fflush(fd_out);
				done = false;
			} else if (strncmp(tmp_stg, "EXIT",
					strnlen(tmp_stg, PERIODIC_MAX_STRLEN))
						== 0) {
				do_cleanup();
				exit(0);
			}

		} while (done != true);
	} else
		usleep(milli*1000);
}
Ejemplo n.º 6
0
static void shell(ssh_session session){
    ssh_channel channel;
    struct termios terminal_local;
    int interactive=isatty(0);
    channel = ssh_channel_new(session);
    if(interactive){
        tcgetattr(0,&terminal_local);
        memcpy(&terminal,&terminal_local,sizeof(struct termios));
    }
    if(ssh_channel_open_session(channel)){
        printf("error opening channel : %s\n",ssh_get_error(session));
        return;
    }
    chan=channel;
    if(interactive){
        ssh_channel_request_pty(channel);
        sizechanged();
    }
    if(ssh_channel_request_shell(channel)){
        printf("Requesting shell : %s\n",ssh_get_error(session));
        return;
    }
    if(interactive){
        cfmakeraw(&terminal_local);
        tcsetattr(0,TCSANOW,&terminal_local);
        setsignal();
    }
    signal(SIGTERM,do_cleanup);
    select_loop(session,channel);
    if(interactive)
    	do_cleanup(0);
}
Ejemplo n.º 7
0
static void do_exit(int i) {
  /* unused variable */
  (void) i;

  do_cleanup(0);
  exit(0);
}
Ejemplo n.º 8
0
int main (int argc, char** argv) {

  // parse the program arguments
  options in_options = options();
  CHECK(parse_arguments(argc, argv, in_options));

  // parse the input graph
  std::unordered_map<uint64_t,cell> graph;
  CHECK(parse_graph(in_options, graph));
  //CHECK(validate_parser(in_options, graph));
  
  // factor the number of partitions
  std::vector<uint64_t> factors(0);
  CHECK(factor(in_options, factors));
  CHECK(validate_factors(in_options, factors));

  // partition!
  CHECK(partition(in_options, graph, factors));

  // write partitions
  CHECK(write_partitions(in_options, graph));

  CHECK(do_cleanup(graph));

  return 0;
}
static void delay(unsigned long milli)
{
	char tmp_stg[PERIODIC_MAX_STRLEN];
	int done;
	int ret;

	if (use_fifo) {
		do {
			done = true;
			ret = fscanf(tReadFifo, "%s", tmp_stg);
			if (ret == 0)
				return;
			if (strncmp(tmp_stg, "PID", strnlen(tmp_stg,
				PERIODIC_MAX_STRLEN)) == 0) {
				fprintf(fd_out, " %u\n", getpid());
				fflush(fd_out);
				done = false;
			} else if (strncmp(tmp_stg, "EXIT",
					strnlen(tmp_stg, PERIODIC_MAX_STRLEN))
						== 0) {
				do_cleanup();
				exit(0);
			}

		} while (done != true);
	} else
		usleep(milli*1000);
}
Ejemplo n.º 10
0
static int
do_polling(void)
{
	int ret = -1, i, nfd;	
	struct epoll_event events[MAX_EVENTS];
	struct _ectl *ectl;
	
	while(!exit_global) {
		if((nfd = epoll_wait(epollfd, events, MAX_EVENTS, -1)) < 0) {
			if (errno == EINTR) {
				continue;
			}
			log_err("epoll_wait(%d) failed %m", epollfd);
			goto clean_up;
		}
		for(i=0; i<nfd; i++) {
			ectl = events[i].data.ptr;
			if (ectl->handler(ECTL2PTR(ectl)) < 0) {
				goto clean_up;
			} 
		}
	}
	ret = 0;
clean_up:
	do_cleanup();
	return ret;
}
Ejemplo n.º 11
0
static void do_exit(int ret)
{
	if (results) {
		printf("\nSummary:\n");
		printf("passed   %d\n", results->passed);
		printf("failed   %d\n", results->failed);
		printf("skipped  %d\n", results->skipped);
		printf("warnings %d\n", results->warnings);

		if (results->passed && ret == TCONF)
			ret = 0;

		if (results->failed)
			ret |= TFAIL;

		if (results->skipped && !results->passed)
			ret |= TCONF;

		if (results->warnings)
			ret |= TWARN;
	}

	do_cleanup();

	exit(ret);
}
Ejemplo n.º 12
0
/* server specific fatal cleanup */
void
cleanup_exit(int i)
{
	if (the_authctxt)
		do_cleanup(the_authctxt);
	_exit(i);
}
Ejemplo n.º 13
0
/**
 * The recursive helper function. It deletes all files inside specified
 * directory and calls itself to delete subdirectories.
 *
 * @param pDirName the directory to delete
 * @param pSep system-dependent file separator
 */
void do_cleanup(const pcsl_string* pDirName, const pcsl_string* pSep)
{
    void* fileList = NULL;
    pcsl_string fileName = PCSL_STRING_NULL;
    pcsl_string dirName  = PCSL_STRING_NULL;

    // add tailing file separator to directory name
    if (pcsl_string_cat(pDirName, pSep, &dirName) != PCSL_STRING_OK) {
        return;
    }

    fileList = pcsl_file_openfilelist(&dirName);
    if (fileList == NULL) {
        pcsl_string_free(&dirName);
        return;
    }

    // iterate over the directory's content
    while (!pcsl_file_getnextentry(fileList, &dirName, &fileName)) {
        int isDir = pcsl_file_is_directory(&fileName);
        if (isDir == 1) {
            // make recursion
            do_cleanup(&fileName, pSep);
        } else {
            // remove file
            pcsl_file_unlink(&fileName);
        }
        pcsl_string_free(&fileName);
    };

    pcsl_string_free(&dirName);
    pcsl_file_closefilelist(fileList);
    // remove empty directory
    pcsl_file_rmdir(pDirName);
}
Ejemplo n.º 14
0
int set_nonblock(int fd) {
    int fl = fcntl(fd, F_GETFL, 0);
    if (fcntl(fd, F_SETFL, fl | O_NONBLOCK) < 0) {
        syslog(LOG_ERR, "fcntl F_SETFL: FD %d: %s", fd, strerror(errno));
        do_cleanup();
        exit(1);
    }
}
Ejemplo n.º 15
0
Archivo: util.c Proyecto: ezpz/ntrace
/**
 * Anything other than SIGINT or a call to _exit calls this function
 */
void exit_fun () {
    TRACE (_state, " [atexit] \n");
    /*
     * It is ok if this is called again when _exit is invoked, a flag is 
     * set to ensure that the process is only dumped once
     */
    do_cleanup (_state);
}
Ejemplo n.º 16
0
/******************************************************************************
 * Close files and plots                                                      *
 ******************************************************************************/
void close_output()
{
    close_glm_ncdf(ncid);
    glm_close_csv_output();

#ifdef PLOTS
    if ( do_plots ) do_cleanup(saveall);
#endif
}
Ejemplo n.º 17
0
PLUGIN_API void	XPluginStop(void)
{
        save_prefs();
        stop_checklists();
        do_cleanup();
        XPLMUnregisterFlightLoopCallback(dataProcessingCallback, NULL);
        XPLMDestroyMenu(checklistsMenu);
        XPLMDestroyMenu(PluginMenu);
        xcClose();
}
Ejemplo n.º 18
0
void tst_vbrk_(const char *file, const int lineno, int ttype,
               const char *fmt, va_list va)
{
	print_result(file, lineno, ttype, fmt, va);

	if (getpid() == main_pid) {
		do_cleanup();
		cleanup_ipc();
	}

	exit(TTYPE_RESULT(ttype));
}
Ejemplo n.º 19
0
int main()
{
	define_exp(exp);
	TRY(exp) {
		do_init();
		launch_resource_process();

		struct bitmap_t * b = load_bitmap("0*XP3:ss_保有背景真アサシン.tlg|FILE:/home/wn/Windows/Fate/image.xp3",
				NULL);
		struct bitmap_array_t * array = split_bitmap(b,
				128, 128, 1);
		if (array->original_bitmap == NULL) {
			free_bitmap(b);
		}
		struct rect_mesh_t * mesh = build_mesh_by_array(array);
		assert(mesh != NULL);

		VERBOSE(SYSTEM, "%dx%d\n", array->nr_w, array->nr_h);
		char name[128];
		for (volatile int j = 0; j < array->nr_h; j++) {
			for (volatile int i = 0; i < array->nr_w; i++) {
				snprintf(name, 128, "/tmp/%dx%d.png", j, i);
				define_exp(exp);
				catch_var(struct io_t *, writer, NULL);
				TRY(exp) {
					set_catched_var(writer, io_open_write("FILE", name));
					bitmap_to_png(&array->tiles[j * array->nr_w + i], writer);
				} FINALLY {
					get_catched_var(writer);
					if (writer != NULL)
						io_close(writer);
				} CATCH(exp) {
					RETHROW(exp);
				}
			}
		}

		print_rect_mesh(mesh);
		destroy_rect_mesh(mesh);

		if (array->original_bitmap != NULL) {
			free_bitmap(array->original_bitmap);
			free_bitmap_array(array);
		}

	} FINALLY {
		shutdown_resource_process();
		do_cleanup();
	} CATCH(exp) {
		
	}
	return 0;
}
Ejemplo n.º 20
0
int main(int argc, char* argv[]){

	char *filepath = NULL;
	char *buf;
	char  tmpfile[64];
	int   interactive;
	ssize_t rc;


	if (argc < 2) {
		fprintf(stderr, "Usage: %s <filepath>\n", argv[0]);
		sprintf(tmpfile, "/tmp/test_auditlog.a1b2c3.%u", getpid());
		fprintf(stderr, "now using file %s\n", tmpfile);
		filepath = tmpfile;
		/* cleanup stale file */
		if (access(tmpfile, W_OK) == 0)
			do_cleanup(tmpfile);
		interactive = 0;
	} else {
		interactive = 1;
		filepath = argv[1];
	}
	buf = malloc(BUF_SIZE);

	rc = open_session_log(filepath);
	assert(rc == 0);

	write_session_info("The name of the log file is: %s\n", filepath);

	sprintf(buf, "This is an entry\n");
	rc = write_session_log(buf, strlen(buf));
	assert(rc == 0);

	close_session_log();

	free(buf);
	if (!interactive)
		do_cleanup(tmpfile);
	return 0;
}
Ejemplo n.º 21
0
void cb_ProcessEventFromIC(VLServer server, VLEvent *ev, void * clientData) {

	char *dataPtr;
	DMbuffer dmbuf;
	int dataBytes;

	int *data = (int *)clientData ;

	printf("From IC made the in %d callback! %s \n", *data, vlEventToName(ev->reason));
	/// reportStatistics();

	switch (ev->reason) {
		case VLTransferComplete:
			while(vlDMBufferGetValid(
				cstate.server, cstate.pathout,
				cstate.memdrn, &dmbuf) == VLSuccess) {

				dataBytes = dmBufferGetSize(dmbuf);
				fprintf(stderr, "from IC dmbuf ok %d bytes at %d\n",
						dataBytes, &dmbuf);

				dmBufferFree(dmbuf);
			}

		break;
		case VLStreamStopped:
			printf("all stop\n");
			do_cleanup() ;
		break;
		case VLSequenceLost:
			printf("Aiiieee - seq lost\n");
			do_cleanup() ;
		break;
		default:
		break;
	}
}
Ejemplo n.º 22
0
void mt_exit(int code)
{
#if 0
  if (cwd) {
    popd();
  }
#endif

  if (cleanup) {
    if (dry_run) 
      fprintf(stderr, "%s: doing cleanup ...\n", progname);
    else
      do_cleanup();
  }
    
  if (newdest) {
    DeleteFile(texfile);
  }

  exit(code);
}
Ejemplo n.º 23
0
/**
 * The function is called upon MIDlet suite removal.
 * It deletes suites's private directory and all it's content.
 *
 * @param suiteId the ID of MIDlet suite
 */
void jsr75_suite_remove_cleanup(SuiteIdType suiteId)
{
    const pcsl_string* pStg = storage_get_root(INTERNAL_STORAGE_ID);
    const jchar jsep = pcsl_file_getfileseparator();

    pcsl_string dirName1 = PCSL_STRING_NULL;
    pcsl_string dirName2 = PCSL_STRING_NULL;
    pcsl_string dirName  = PCSL_STRING_NULL;
    pcsl_string sep      = PCSL_STRING_NULL;

    if (pcsl_string_convert_from_utf16(&jsep, 1, &sep) != PCSL_STRING_OK) {
        return;
    }
    if (pcsl_string_cat(pStg, &privateDir, &dirName1) != PCSL_STRING_OK) {
        pcsl_string_free(&sep);
        return;
    }
    if (pcsl_string_cat(&dirName1, &sep, &dirName2) != PCSL_STRING_OK) {
        pcsl_string_free(&sep);
        pcsl_string_free(&dirName1);
        return;
    }
    if (pcsl_string_cat(&dirName2, midp_suiteid2pcsl_string(suiteId),
            &dirName) != PCSL_STRING_OK) {
        pcsl_string_free(&sep);
        pcsl_string_free(&dirName1);
        pcsl_string_free(&dirName2);
        return;
    }
    pcsl_string_free(&dirName1);
    pcsl_string_free(&dirName2);

    do_cleanup(&dirName, &sep);

    pcsl_string_free(&sep);
    pcsl_string_free(&dirName);
}
Ejemplo n.º 24
0
static int GGIopen(ggi_visual *vis, struct ggi_dlhandle *dlh,
		   const char *args, void *argptr, uint32_t *dlret)
{
	ggi_lcd823_priv *priv;
	int size;

	DPRINT("display-lcd823: GGIopen start.\n");

	LIBGGI_PRIVATE(vis) = priv = malloc(sizeof(ggi_lcd823_priv));
	if (priv == NULL) {
		return GGI_ENOMEM;
	}
	
	priv->fb_ptr = NULL;

	/* Now open the framebuffer device */
	LIBGGI_FD(vis) = open(LCD_DEVNAME, O_RDWR);
	if (LIBGGI_FD(vis) < 0) {
		fprintf(stderr, "display-lcd823: Couldn't open "
			"framebuffer device %s: %s\n", LCD_DEVNAME,
			strerror(errno));
		do_cleanup(vis);
		return GGI_ENODEVICE;
	}
	if (ioctl(LIBGGI_FD(vis), 1) != 0) {
		fprintf(stderr, "display-lcd823: Unable to enable LCD: %s\n",
			strerror(errno));
		do_cleanup(vis);
		return GGI_ENODEVICE;
	}
	if (ioctl(LIBGGI_FD(vis), 5, &size) != 0) {
		fprintf(stderr, "display-lcd823: Unable to get size of LCD "
			"memory: %s\n",
			strerror(errno));
		do_cleanup(vis);
		return GGI_ENODEVICE;
	}

	priv->fb_size = size * getpagesize();
	priv->fb_ptr = mmap(NULL, priv->fb_size, PROT_READ | PROT_WRITE,
			    MAP_SHARED, LIBGGI_FD(vis), 0);
	if (priv->fb_ptr == MAP_FAILED) {
		fprintf(stderr, "display-lcd823: Unable to map LCD "
			"memory: %s\n",
			strerror(errno));
		priv->fb_ptr = NULL;
		do_cleanup(vis);
		return GGI_ENODEVICE;
	}
	priv->frame_size = priv->fb_size;

	LIBGGI_GC(vis) = malloc(sizeof(ggi_gc));
	if (LIBGGI_GC(vis) == NULL) {
		do_cleanup(vis);
		return GGI_ENOMEM;
	}

	/* Mode management */
	vis->opdisplay->getmode   = GGI_lcd823_getmode;
	vis->opdisplay->setmode   = GGI_lcd823_setmode;
	vis->opdisplay->checkmode = GGI_lcd823_checkmode;
	vis->opdisplay->getapi    = GGI_lcd823_getapi;
	vis->opdisplay->flush     = GGI_lcd823_flush;
	vis->opdisplay->setflags  = GGI_lcd823_setflags;

	/* Register cleanup handler */
	ggRegisterCleanup((ggcleanup_func *)do_cleanup, vis);

	DPRINT("display-lc823: GGIopen success.\n");

	*dlret = GGI_DL_OPDISPLAY;
	return 0;
}
Ejemplo n.º 25
0
int main(int argc, char* argv[])
{
  struct rtt_options opts;
  opts.ping_frame_len = 42;
  opts.pong_frame_len = 42;
  opts.n_warm_ups = 10000;
  opts.n_iters = 100000;
  opts.inter_iter_gap_ns = 0;

  int c;
  while( (c = getopt(argc, argv, "i:w:f:g:h")) != -1 )
    switch( c ) {
    case 'i':
      opts.n_iters = atoi(optarg);
      break;
    case 'w':
      opts.n_warm_ups = atoi(optarg);
      break;
    case 'f':
      opts.ping_frame_len = atoi(optarg);
      opts.pong_frame_len = atoi(optarg);
      break;
    case 'g':
      opts.inter_iter_gap_ns = atoi(optarg);
      break;
    case 'h':
      usage_msg(stdout);
      exit(0);
      break;
    case '?':
      usage_err();
    default:
      RTT_TEST( 0 );
    }

  argc -= optind;
  argv += optind;
  if( argc < 2 || argc > 3 )
    usage_err();
  const char* action = argv[0];
  const char* tx_ep_spec = argv[1];
  const char* rx_ep_spec = (argc >= 3) ? argv[2] : NULL;

  struct rtt_endpoint* tx_ep;
  if( spec_to_endpoint(&tx_ep, &opts,
                       RTT_DIR_TX | ((rx_ep_spec) ? 0 : RTT_DIR_RX),
                       tx_ep_spec) < 0 )
    return 2;
  struct rtt_endpoint* rx_ep;
  if( rx_ep_spec != NULL ) {
    if( spec_to_endpoint(&rx_ep, &opts, RTT_DIR_RX, rx_ep_spec) < 0 )
      return 3;
  }
  else {
    rx_ep = tx_ep;
  }

  if( ! strcmp(action, "ping") )
    do_pinger(&opts, tx_ep, rx_ep);
  else if( ! strcmp(action, "pong") )
    do_ponger(&opts, tx_ep, rx_ep);
  else
    usage_err();

  do_cleanup(tx_ep, rx_ep);
  return 0;
}
Ejemplo n.º 26
0
static int GGIclose(ggi_visual *vis, struct ggi_dlhandle *dlh)
{
	return do_cleanup(vis);
}
Ejemplo n.º 27
0
void cleanup(int sig) {
    do_cleanup();
    exit(0);
}
Ejemplo n.º 28
0
int __cdecl main(int argc, char **argv)
{
    DWORD TheResult;
    DWORD initialAttr;
    CHAR *FileName_Multibyte = "test_file";
    WCHAR FileName[MAX_PATH];

    if (0 != PAL_Initialize(argc,argv))
    {
        return FAIL;
    }

    // Create the test file
    FILE *testFile = fopen(FileName_Multibyte, "w");
    if (testFile == NULL)
    {
        Fail("Unexpected error: Unable to open file %S with fopen. \n", FileName);
    }
    if (fputs("testing", testFile) == EOF)
    {
        Fail("Unexpected error: Unable to write to file %S with fputs. \n", FileName);
    }
    if (fclose(testFile) != 0)
    {
        Fail("Unexpected error: Unable to close file %S with fclose. \n", FileName);
    }
    testFile = NULL;

    /* Make a wide character string for the file name */

    MultiByteToWideChar(CP_ACP,
                        0,
                        FileName_Multibyte,
                        -1,
                        FileName,
                        MAX_PATH);

    /* Get the initial attributes of the file */
    initialAttr = GetFileAttributesW(FileName);

    /* Try to set the file to HIDDEN */

    TheResult = SetFileAttributes(FileName,FILE_ATTRIBUTE_HIDDEN);

    if(TheResult == 0)
    {
        do_cleanup(FileName,initialAttr);
        Fail("ERROR: SetFileAttributes returned 0, failure, when trying "
             "to set the FILE_ATTRIBUTE_HIDDEN attribute.  This should "
             "not do anything in FreeBSD, but it shouldn't fail.");
    }

    /* Try to set the file to ARCHIVE */

    TheResult = SetFileAttributes(FileName,FILE_ATTRIBUTE_ARCHIVE);

    if(TheResult == 0)
    {
        do_cleanup(FileName,initialAttr);
        Fail("ERROR: SetFileAttributes returned 0, failure, when trying "
             "to set the FILE_ATTRIBUTE_ARCHIVE attribute.");
    }

    /* Try to set the file to SYSTEM */

    TheResult = SetFileAttributes(FileName,FILE_ATTRIBUTE_SYSTEM);

    if(TheResult == 0)
    {
        do_cleanup(FileName,initialAttr);
        Fail("ERROR: SetFileAttributes returned 0, failure, when trying "
             "to set the FILE_ATTRIBUTE_SYSTEM attribute.");
    }

    /* Try to set the file to DIRECTORY */

    TheResult = SetFileAttributes(FileName,FILE_ATTRIBUTE_DIRECTORY);

    if(TheResult == 0)
    {
        do_cleanup(FileName,initialAttr);
        Fail("ERROR: SetFileAttributes returned 0, failure, when trying "
             "to set the FILE_ATTRIBUTE_DIRECTORY attribute.");
    }

    do_cleanup(FileName,initialAttr);
    PAL_Terminate();
    return PASS;
}
Ejemplo n.º 29
0
main(int argc, char **argv)
{
    int i,j;
    int c;
    extern char *optarg;
    int ctrproc;
    int start;
    int proc_size;
    char name[32];

    /*********************************************************************
      Parse the command line
      ********************************************************************/
    collect_info = 1;
    MEMSYS_OFF;                             /* in the initialization phase */
    while ((c = getopt(argc, argv, "p:s:b:BdvH")) != -1) {
        switch(c) {
        case 'p':
            NUM_PROCS = atoi(optarg);
            if (NUM_PROCS < 1) {
                printf("P must be >= 1\n");
                exit(-1);
            }
            break;

        case 's':
            size = atoi(optarg);
            break;

        case 'b':
            BubbleThresh = atoi(optarg);
            break;

        case 'B':
            bubble = 1;
            break;
        case 'd':
            show_array = 1;
            break;
        case 'v':
            verify = 1;
            break;
        default:
            printf("Bad option : %s \n",optarg);
        case 'h':
            printf( "\t\t\tQS - OPTIONS\n");
            printf( "\tp - Number of processors\n");
            printf( "\ts - Size of array\n");
            printf( "\tb - Bubble threshold\n");
            printf( "\tB - Bubble\n");
            printf( "\td - Display output \n");
            printf( "\tv - Verify results \n");
            printf( "\tH - Help\n");
            exit(0);
        }
    }

    StatClearAll();         /* clear the stats */
    /**********************************************************************/
    /* Use shmalloc to allocate memory from the shared address space, also
       use AssociateAddrNode to determine the distribution of the shared
       memory among the various processors */
    /**********************************************************************/
    gMem = (GlobalMemory *) shmalloc(sizeof(GlobalMemory));
    ctrproc = NUM_PROCS/2  + (int)(sqrt((double)NUM_PROCS)/2);
    /* choose a "middle-point" in the mesh network */

    /* associate the task stack variables to a processor easily accessible */
#if !defined(SPATIAL)
    AssociateAddrNode((void *)&(gMem->TaskStackLock),
                      (void *)(&(gMem->NumWaiting)+1),
                      ctrproc>=NUM_PROCS-1? NUM_PROCS-1 :  ctrproc+1,"lock");
    AssociateAddrNode((void *)&(gMem->TaskStackTop),
                      (void *)(&(gMem->TaskStackTop)+1),
                      ctrproc>=NUM_PROCS-1 ? NUM_PROCS-1 : ctrproc,"top");
#endif

    /************** associate the task queue among all processors *********/
    chunk = MAX_TASK_QUEUE / NUM_PROCS;
    for (i=0; i< NUM_PROCS; i++)   {
#if !defined(SPATIAL)
        AssociateAddrNode(&gMem->tasks[i*chunk],
                          &gMem->tasks[(i+1)*chunk],
                          i,"tasks");
#endif
    }
    LocalStackTop = -1;
    FREELOCK(&gMem->TaskStackLock);
    proc_size = (size + NUM_PROCS)/NUM_PROCS;

    /*************** associate the array among all processors **************/
    start = 0;
    strcpy(name,"Array chunks");
    for(i=0; i<NUM_PROCS; i++) {
        printf("going to call Associate address node\n");
#if !defined(SPATIAL)&&!defined(DO_PREF)
        AssociateAddrNode(&gMem->A[start],
                          &gMem->A[start+ proc_size],
                          i, name);
#endif
        start = start+proc_size;
    }

    printf( "QS - OPTIONS\n");
    printf( "\tp - Number of processors \t%d\n", NUM_PROCS);
    printf( "\ts - Size of array\t\t%d\n",size);
    printf( "\tb - Bubble threshold \t\t%d\n",BubbleThresh);
    printf( "\tB - Bubble \t\t\t%d\n",bubble);
    printf( "\td - Display output\t\t%d\n",show_array);
    printf( "\tv - Verify results\t\t%d\n",verify);

    /* The work which the root process has to do */
    whoami=0;
    root_main();                  /* initialization by the root process */
    endphase(phase);              /* end of initialization phase */
    TreeBarInit(&tree,NUM_PROCS); /* initialize tree barrier */

    MEMSYS_ON;

    /********************************************************************/
    /* Forking processes :  Create a process for each of the processors */
    /********************************************************************/

    for(i=0; i<NUM_PROCS-1; i++) {
        if(fork() == 0)     {
            whoami =  getpid();
            LocalStackTop = -1;
            for (i = (whoami+1) * chunk -1; i > whoami * chunk; i--) {
                LocalTaskStack[++LocalStackTop] = i;
            }
            break;
        }
    }

    /******************* Barrier after initialization *******************/
    printf("Before barrier %d\n",whoami);
    TreeBarrier(&tree,whoami);
    printf("Starting Process %d\n",whoami);
    if (whoami == 0)     {
        StatReportAll();
        StatClearAll();
    }

    newphase(++phase);
    Worker();   /**** Call the main procedure which we have to execute ****/
    endphase(phase);

    /**************** Barrier after finishing the sort ******************/
    printf("Coming out of worker %d\n",whoami);
    TreeBarrier(&tree,whoami);
    MEMSYS_OFF;
    if (whoami == 0)     {
        StatReportAll();
        StatClearAll();
    }

    /*************************** Cleanup phase ***************************/
    newphase(++phase);
    if(whoami== 0)     do_cleanup();
    endphase(phase);
    if (whoami == 0)     {
        StatReportAll();
        StatClearAll();
    }
}
Ejemplo n.º 30
0
int main()
{
	struct Game *game = malloc(sizeof(struct Game));
	char buf[BUFSIZ];
	char *index;
	char *arg[4];
	int arg_num;

	while (fgets(buf, sizeof(buf), stdin) != NULL) {
		index = buf;
		arg_num = 0;
		arg[arg_num] = index;
		for (;(*index != '\n'); index++) {
			if (*index == ' ') {
				*index = '\0';
				arg[arg_num+1] = index+1;
				arg_num++;
			}
		}
		*index = '\0';

		if (!strcmp(arg[0], "turn")) {
			game->turn = atoi(arg[1]);
			fprintf(stderr, "Got turn %d\n", game->turn);
			if (game->turn) {
				game->state = INGAME;
				do_preturn(game);
			} else {
				game->state = SETUP;
			}
		} else if (!strcmp(arg[0], "end")) {
			break;
		}

		if (game->state == SETUP) {
			if (!strcmp(arg[0], "loadtime")) {
				game->loadtime = atoi(arg[1]);
			} else if (!strcmp(arg[0], "turntime")) {
				game->turntime = atoi(arg[1]);
			} else if (!strcmp(arg[0], "rows")) {
				game->rows = atoi(arg[1]);
			} else if (!strcmp(arg[0], "cols")) {
				game->cols = atoi(arg[1]);
			} else if (!strcmp(arg[0], "turns")) {
				game->turns = atoi(arg[1]);
			} else if (!strcmp(arg[0], "viewradius2")) {
				game->viewradius2 = atoi(arg[1]);
			} else if (!strcmp(arg[0], "attackradius2")) {
				game->attackradius2 = atoi(arg[1]);
			} else if (!strcmp(arg[0], "spawnradius2")) {
				game->spawnradius2 = atoi(arg[1]);
			} else if (!strcmp(arg[0], "player_seed")) {
				game->player_seed = atoi(arg[1]);
			} else if (!strcmp(arg[0], "ready")) {
				do_setup(game);
				fprintf(stdout, "go\n");
				fflush(NULL);
			}
		} else {
			int row,col,owner;
			switch (*arg[0]) {
				case 'w':
					row = atoi(arg[1]);
					col = atoi(arg[2]);
					game->watermap[loc(row,col)] = 1;
					break;
				case 'f':
					row = atoi(arg[1]);
					col = atoi(arg[2]);
					game->foodmap[loc(row,col)] = 1;
					break;
				case 'h':
					row = atoi(arg[1]);
					col = atoi(arg[2]);
					owner = atoi(arg[3]);
					game->hillmap[loc(row,col)] = owner+1;
					break;
				case 'a':
					row = atoi(arg[1]);
					col = atoi(arg[2]);
					owner = atoi(arg[3]);
					game->antmap[loc(row,col)] = owner+1;
					break;
				case 'd':
					// Dead ants, meh
					break;
			}
			if (!strcmp(arg[0], "go")) {
				do_turn(game);
				fprintf(stdout, "go\n");
				fflush(NULL);
			}
		}
	}
	do_cleanup(game);
	return 0;
}