Exemple #1
0
/*
 * pthread_create takes its fn parameter as void *(*)(void*), so
 * Thread->fn itself cannot be passed to it.  This has the proper signature
 * and wraps Thread->fn.  It also initialises thread-local storage and
 * waits for the Thread structure to be completely filled out before
 * finally starting the thread's main procedure.
 */
static void*
run(void *arg)
{
	Thread *t;
	
	t = (Thread*)arg;
	dprintf("thread %p spawn\n", t);
	pthread_once(&tlsonce, construct);
	pthread_setspecific(tlskey, t);
	initrand(&t->r);
	lock(&t->runwait, 1);
	unlock(&t->runwait);
	destroylock(&t->runwait);
	dprintf("thread %p run\n", t);
	t->fn(t->arg);
	return nil;
}
Exemple #2
0
void InitSimpleStuff(void) {

    initlibrarysearchpath();
    initlibltdl();
    initrand();
    initadobeenc();

    setlocale(LC_ALL,"");
    localeinfo = *localeconv();
    coord_sep = ",";
    if ( *localeinfo.decimal_point=='.' ) coord_sep=",";
    else if ( *localeinfo.decimal_point!='.' ) coord_sep=" ";
    if ( getenv("FF_SCRIPT_IN_LATIN1") ) use_utf8_in_script=false;

    inituninameannot();	/* Note: unicodenames done after locales set */

    SetDefaults();
}
Exemple #3
0
int main(int argc,char**argv){
	glfwInit();
	GLFWwindow*wnd=glfwCreateWindow(512,512,0,0,0);
	glfwMakeContextCurrent(wnd);
	glOrtho(0,512,512,0,1,-1);
	initrand();
	union{struct{uint16_t x,y;};uint32_t z;}tail[7396];
	die:;
	int tlen=1,apx=tail->x=256,apy=tail->y=256,dir=0;
	for(;;){
		glClear(GL_COLOR_BUFFER_BIT);
		int dx=glfwGetKey(wnd,GLFW_KEY_RIGHT)-glfwGetKey(wnd,GLFW_KEY_LEFT),dy=glfwGetKey(wnd,GLFW_KEY_DOWN)-glfwGetKey(wnd,GLFW_KEY_UP);
		if(!dx!=!dy){
			int d=dx?1-dx:2-dy;
			if((d&1)!=(dir&1))dir=d;
		}
		memmove(tail+1,tail,(tlen-1)*4);
		switch(dir){
		case 0:tail->x+=8;
		break;case 1:tail->y+=8;
		break;case 2:tail->x-=8;
		break;case 3:tail->y-=8;
		break;default:__builtin_unreachable();
		}
		if(tail->z&33554944)goto die;
		glColor3ub(0,255,0);
		for(int i=0;i<tlen;i++){
			if(i>2&&abs(tail[i].x-tail->x)<12&&abs(tail[i].y-tail->y)<12)goto die;
			glRecti(tail[i].x-8,tail[i].y-8,tail[i].x+8,tail[i].y+8);
			if(abs(tail[i].x-apx)<20&&abs(tail[i].y-apy)<20){
				do apx=rand()&511; while(apx<32||apx>480);
				do apy=rand()&511; while(apy<32||apy>480);
				tail[tlen]=tail[tlen-1];
				tlen++;
			}
		}
		glColor3ub(255,0,0);
		glRecti(apx-12,apy-12,apx+12,apy+12);
		glfwSwapBuffers(wnd);
		endframe(50);
		glfwPollEvents();
		if(glfwGetKey(wnd,GLFW_KEY_ESCAPE)||glfwWindowShouldClose(wnd))return 0;
	}
}
int main(int argc, char *argv[]) {

	// Validate command line arguments
	if(argc !=3 ) {
		fprintf(stderr, "Expected usage:  %s <width> <height>\n", argv[0]);
		return EXIT_FAILURE;
	}
	
	// Get width and height from command line
	int h = atoi(argv[2]), w = atoi(argv[1]);
	
	// Translate to form needed by amaze.c
	int rows = (h-1)/2, cols = (w-1)/2;

	// Create maze
	initrand();
	char** maze = mazeinit(rows, cols, 'X');
	mazewalk(maze,rows,cols);

	// Print maze
	int y,x;
	for(y=0; y < h; y++) {
		for(x=0; x < w; x++) {
			putchar(maze[y][x]);
		}
		putchar('\n');
	}

	// Print divider
	printf("\n\n");

	// Call student code
	print_directions(maze, w, h);

	// Free maze memory
	mazefree(maze, rows);

	return EXIT_SUCCESS;
}
Exemple #5
0
int
main(int argc, char *argv[])
{
    char *progname;
    unsigned c;
    extern char *optarg;
    unsigned nprocs = 0;
    unsigned procno;
    pid_t *pidarray=NULL;
    pid_t pid;
    uchar_t *buf, *ptr;
    unsigned int seed;
    int alarmtime = 0;
    struct sigaction sa;
    unsigned i, j;
    uchar_t data;
    int no_prob = 0;
    time_t t;
    int wait_stat;

    progname = *argv;
    pagesize = sysconf(_SC_PAGE_SIZE);

    if (argc < 2) {
        (void)fprintf(stderr, "usage: %s %s\n", progname, usage);
        anyfail();
    }

    while ((c = getopt(argc, argv, "mdrp:t:s:")) != -1) {
        switch (c) {
        case 'd':
            debug = 1;
            break;
        case 't':
            alarmtime = atoi(optarg) * 60;
            break;
        case 'p':
            nprocs = atoi(optarg);
            break;
        case 'm':
            dosync = 1;
            break;
        case 's':
            mapsize = atoi(optarg);
            if (mapsize < 0) {
                (void)fprintf(stderr, "error: negative "
                              "mapsize\n");
                anyfail();
            }
            break;
        case 'r':
            randloops = 1;
            break;
        default:
            (void)fprintf(stderr, "usage: %s %s\n", progname,
                          usage);
            anyfail();
        }
    }

    /* nprocs is unsigned */
    if (nprocs > 255) {
        (void)fprintf(stderr, "invalid nprocs %d - (range 0-255)\n",
                      nprocs);
        anyfail();
    }
    (void)time(&t);
//	(void)printf("%s: Started %s", argv[0], ctime(&t)); LTP Port

    seed = initrand();
    pattern = seed & 0xff;

    if (debug) {
        (void)printf("%s mapsize %d bytes, pattern %d\n",
                     progname, mapsize, pattern);
        if (alarmtime)
            (void)printf("running for %d minutes\n", alarmtime/60);
        else
            (void)printf("running with no time limit\n");
    }

    if ((mapaddr = mmap(0, mapsize, PROT_READ|PROT_WRITE,
                        MAP_ANONYMOUS|MAP_SHARED, 0, 0))
            == (caddr_t)-1) {
        perror("mmap error");
        anyfail();
    }

    if ((buf = (uchar_t *)malloc(pagesize)) == NULL
            || (pidarray = (pid_t *)malloc(nprocs*sizeof(pid_t))) == NULL) {
        perror("malloc error");
        anyfail();
    }

    for (i = 0; i < nprocs; i++)
        *(pidarray+i) = 0;

    /*
     * Initialize page compare buffer, then initialize map.
     */

    for (i = 0, data = 0; i < pagesize; i++) {
        *(buf+i) = (data + pattern) & 0xff;
        if (++data == nprocs)
            data = 0;
    }

    mappages = roundup(mapsize, pagesize)/pagesize;
    ptr = (uchar_t *)mapaddr;

    for (i = 0; i < mappages; i++) {
        for (j = 0; j < pagesize; j++)
            *ptr++ = *(buf+j);
    }

    /*
     *  Fork off mmap children.
     */
    for (procno = 0; procno < nprocs; procno++) {
        switch (pid = fork()) {

        case -1:
            perror("fork error");
            goto cleanup;

        case 0:
            child_mapper(procno, nprocs);
            exit(0);

        default:
            pidarray[procno] = pid;
        }
    }

    /*
     *  Plan for death by signal.  User may have specified
     *  a time limit, in which set an alarm and catch SIGALRM.
     *  Also catch and cleanup with SIGINT.
     */
    sa.sa_handler = finish;
    sa.sa_flags = 0;
    if (sigemptyset(&sa.sa_mask)) {
        perror("sigemptyset error");
        goto cleanup;
    }

    if (sigaction(SIGINT, &sa, 0) == -1) {
        perror("sigaction error");
        goto cleanup;
    }

    if (alarmtime) {
        if (sigaction(SIGALRM, &sa, 0) == -1) {
            perror("sigaction error");
            goto cleanup;
        }
        (void)alarm(alarmtime);
    }

    /*
     *  Now wait for children and refork them as needed.
     */

    while (!finished) {
        do {
            pid = wait(&wait_stat);
        } while (pid == -1 && errno == EINTR);
        /*
         *  Block signals while processing child exit.
         */

        if (sighold(SIGALRM) || sighold(SIGINT)) {
            perror("sighold error");
            goto cleanup;
        }

        if (pid != -1) {
            /*
             *  Check exit status, then refork with the
             *  appropriate procno.
             */
            if (!WIFEXITED(wait_stat)
                    || WEXITSTATUS(wait_stat) != 0) {
                (void)fprintf(stderr, "child exit with err "
                              "<x%x>\n", wait_stat);
                goto cleanup;
            }
            for (i = 0; i < nprocs; i++)
                if (pid == pidarray[i])
                    break;
            if (i == nprocs) {
                (void)fprintf(stderr,
                              "unknown child pid %d, <x%x>\n",
                              pid, wait_stat);
                goto cleanup;
            }

            if ((pid = fork()) == -1) {
                perror("fork error");
                pidarray[i] = 0;
                goto cleanup;
            } else if (pid == 0) {		/* child */
                child_mapper(i, nprocs);
                exit(0);
            } else
                pidarray[i] = pid;
        } else {
            /*
             *  wait returned an error.  If EINTR, then
             *  normal finish, else it's an unexpected
             *  error...
             */
            if (errno != EINTR || !finished) {
                perror("unexpected wait error");
                goto cleanup;
            }
        }
        if (sigrelse(SIGALRM) || sigrelse(SIGINT)) {
            perror("sigrelse error");
            goto cleanup;
        }
    }

    /*
     *  Finished!  Check the map for sanity, then kill all
     *  the children and done!.
     */

    if (sighold(SIGALRM)) {
        perror("sighold error");
        goto cleanup;
    }
    (void)alarm(0);
    no_prob = 1;

cleanup:
    for (i = 0; i < nprocs; i++)
        (void)kill(pidarray[i], SIGKILL);	/* failure? oh well. */

    while (wait(&wait_stat) != -1 || errno != ECHILD)
        continue;

    if (no_prob) {		/* only check file if no errors */
        if (!mapokay(buf)) {
            (void)fprintf(stderr, "map data incorrect!\n");
            anyfail();
        }
        else
            (void)printf("map data okay\n");
    }

    (void)time(&t);
//	(void)printf("%s: Finished %s", argv[0], ctime(&t)); LTP POrt
    ok_exit();
    return(0);
}
Exemple #6
0
/* loads the city level */
void load_city(int populate)
{
    int i,j;
    pml ml;
    char site;
    map *city;
    map *maze;

    initrand(E_CITY, 0);

    /* Get the hedge maze (which is in the city). */
    maze = map_open(MAP_hedges);
    /* Choose a random level from it. */
    map_setLevel(maze, random_range(map_getDepth(maze)));

    /* Get the city. */
    city = map_open(MAP_city);
    map_setLevel(city,0);

    TempLevel = Level;
    if (ok_to_free(TempLevel)) {
#ifndef SAVE_LEVELS
        free_level(TempLevel);
#endif
        TempLevel = NULL;
    }
#ifndef SAVE_LEVELS
    Level = ((plv) checkmalloc(sizeof(levtype)));
#else
    msdos_changelevel(TempLevel,0,-1);
    Level = &TheLevel;
#endif
    clear_level(Level);
    Level->depth = 0;
    Level->environment = E_CITY;

    /* WDT: Rampart, as a special case, has its width stored in a
    * global variable. */
    WIDTH = Level->level_width = map_getWidth(city);
    LENGTH = Level->level_length = map_getLength(city);

    for(j=0; j<Level->level_length; j++) {
        for(i=0; i<Level->level_width; i++) {
            lset(i,j,SEEN);
            site = map_getSiteChar(city,i,j);
            switch(site) {
                /*
                case '@':
                Player.x = i; Player.y = j;
                Level->site[i][j].locchar = FLOOR;
                break;
                */
            case 'g':
                Level->site[i][j].locchar = FLOOR;
                Level->site[i][j].p_locf = L_GARDEN;
                break;
            case 'y':
                Level->site[i][j].locchar = FLOOR;
                Level->site[i][j].p_locf = L_CEMETARY;
                break;
            case 'p': /* WDT: each of these places needs to be assigned
					  * a function (or replaced with an 'x' in the map)
					  */
            case '!':
            case 'I':
            case 'E':
            case 'e':
            case 'x':
                assign_city_function(i,j);
                break;
            case 't':
                Level->site[i][j].locchar = FLOOR;
                Level->site[i][j].p_locf = L_TEMPLE;
                CitySiteList[L_TEMPLE-CITYSITEBASE][0] = TRUE;
                CitySiteList[L_TEMPLE-CITYSITEBASE][1] = i;
                CitySiteList[L_TEMPLE-CITYSITEBASE][2] = j;
                break;
#if 0 /* WDT: HACK!  The new city doesn't use portcullis traps, but has other
                * uses for 'T'.  Um...  I'd rather have a use for them (that's what
                * the jail is supposed to be), so this will stay only for now; with
                    * any luck we'll have things fixed up before the next release. */
                    case 'T':
                    Level->site[i][j].locchar = FLOOR;
                    Level->site[i][j].p_locf = L_PORTCULLIS_TRAP;
                    Level->site[i][j].aux = NOCITYMOVE;
                    break;
#endif /* end of hack */
                    case 'R':
                    Level->site[i][j].locchar = FLOOR;
                    Level->site[i][j].p_locf = L_RAISE_PORTCULLIS;
                    Level->site[i][j].aux = NOCITYMOVE;
                    break;
                    case '7':
                    Level->site[i][j].locchar = FLOOR;
                    Level->site[i][j].p_locf = L_PORTCULLIS;
                    Level->site[i][j].aux = NOCITYMOVE;
                    break;
                    case 'C':
                    Level->site[i][j].locchar = OPEN_DOOR;
                    Level->site[i][j].p_locf = L_COLLEGE;
                    CitySiteList[L_COLLEGE-CITYSITEBASE][0] = TRUE;
                    CitySiteList[L_COLLEGE-CITYSITEBASE][1] = i;
                    CitySiteList[L_COLLEGE-CITYSITEBASE][2] = j;
                    break;
                    case 's':
                    Level->site[i][j].locchar = OPEN_DOOR;
                    Level->site[i][j].p_locf = L_SORCERORS;
                    CitySiteList[L_SORCERORS-CITYSITEBASE][0] = TRUE;
                    CitySiteList[L_SORCERORS-CITYSITEBASE][1] = i;
                    CitySiteList[L_SORCERORS-CITYSITEBASE][2] = j;
                    break;
                    case 'M':
                    Level->site[i][j].locchar = OPEN_DOOR;
                    Level->site[i][j].p_locf = L_MERC_GUILD;
                    CitySiteList[L_MERC_GUILD-CITYSITEBASE][0] = TRUE;
                    CitySiteList[L_MERC_GUILD-CITYSITEBASE][1] = i;
                    CitySiteList[L_MERC_GUILD-CITYSITEBASE][2] = j;
                    break;
                    case 'K':
                    Level->site[i][j].locchar = OPEN_DOOR;
                    Level->site[i][j].p_locf = L_MONASTERY;
                    CitySiteList[L_MONASTERY-CITYSITEBASE][0] = TRUE;
                    CitySiteList[L_MONASTERY-CITYSITEBASE][1] = i;
                    CitySiteList[L_MONASTERY-CITYSITEBASE][2] = j;
                    break;
                    case 'c':
                    Level->site[i][j].locchar = OPEN_DOOR;
                    Level->site[i][j].p_locf = L_CASTLE;
                    CitySiteList[L_CASTLE-CITYSITEBASE][0] = TRUE;
                    CitySiteList[L_CASTLE-CITYSITEBASE][1] = i;
                    CitySiteList[L_CASTLE-CITYSITEBASE][2] = j;
                    break;
                    case '?':
            {
                static int myI = -1, myJ;
                char site;
                if ( myI == -1 )
            {
                /* If this is the first time we've seen the hedge maze,
                * set this as its corner. */
                myI = i;
                myJ = j;
            }
    site = map_getSiteChar(maze, i - myI, j - myJ);
        mazesite(site,i,j,populate);
    }
    break;
    case 'P':
        Level->site[i][j].locchar = OPEN_DOOR;
        Level->site[i][j].p_locf = L_ORDER;
        CitySiteList[L_ORDER-CITYSITEBASE][0] = TRUE;
        CitySiteList[L_ORDER-CITYSITEBASE][1] = i;
        CitySiteList[L_ORDER-CITYSITEBASE][2] = j;
        break;
    case 'H':
        Level->site[i][j].locchar = OPEN_DOOR;
        Level->site[i][j].p_locf = L_CHARITY;
        CitySiteList[L_CHARITY-CITYSITEBASE][0] = TRUE;
        CitySiteList[L_CHARITY-CITYSITEBASE][1] = i;
        CitySiteList[L_CHARITY-CITYSITEBASE][2] = j;
        break;
    case 'h':
        Level->site[i][j].locchar = FLOOR;
        if (populate)
            make_horse(i,j); /* from village.c */
        break;
    case 'j':
        Level->site[i][j].locchar = FLOOR;
        if (populate)
            make_justiciar(i,j);
        break;
    case 'J':
        Level->site[i][j].locchar = CLOSED_DOOR;
        Level->site[i][j].p_locf = L_JAIL;
        break;
    case 'A':
        Level->site[i][j].locchar = OPEN_DOOR;
        Level->site[i][j].p_locf = L_ARENA;
        CitySiteList[L_ARENA-CITYSITEBASE][0] = TRUE;
        CitySiteList[L_ARENA-CITYSITEBASE][1] = i;
        CitySiteList[L_ARENA-CITYSITEBASE][2] = j;
        break;
    case 'B':
        Level->site[i][j].locchar = OPEN_DOOR;
        Level->site[i][j].p_locf = L_BANK;
        CitySiteList[L_BANK-CITYSITEBASE][0] = TRUE;
        CitySiteList[L_BANK-CITYSITEBASE][1] = i;
        CitySiteList[L_BANK-CITYSITEBASE][2] = j;
        lset(i,j,STOPS);
        lset(i,j+1,STOPS);
        lset(i+1,j,STOPS);
        lset(i-1,j,STOPS);
        lset(i,j-1,STOPS);
        break;
    case 'i':
        Level->site[i][j].locchar = OPEN_DOOR;
        Level->site[i][j].p_locf = L_TOURIST;
        CitySiteList[L_TOURIST-CITYSITEBASE][1] = i;
        CitySiteList[L_TOURIST-CITYSITEBASE][2] = j;
        lset(i,j,STOPS);
        lset(i,j+1,STOPS);
        lset(i+1,j,STOPS);
        lset(i-1,j,STOPS);
        lset(i,j-1,STOPS);
        break;
    case 'X':
        Level->site[i][j].locchar = FLOOR;
        Level->site[i][j].p_locf = L_COUNTRYSIDE;
        CitySiteList[L_COUNTRYSIDE-CITYSITEBASE][0] = TRUE;
        CitySiteList[L_COUNTRYSIDE-CITYSITEBASE][1] = i;
        CitySiteList[L_COUNTRYSIDE-CITYSITEBASE][2] = j;
        break;
    case 'v':
        Level->site[i][j].locchar = FLOOR;
        Level->site[i][j].p_locf = L_VAULT;
        Level->site[i][j].aux = NOCITYMOVE;
        lset(i,j,SECRET);
        break;
    case 'S':
        Level->site[i][j].locchar = FLOOR;
        Level->site[i][j].aux = NOCITYMOVE;
        lset(i,j,SECRET);
        break;
    case 'G':
        Level->site[i][j].locchar = FLOOR;
        if (populate) {
            make_site_monster(i,j,GUARD);
            Level->site[i][j].creature->aux1 = i;
            Level->site[i][j].creature->aux2 = j;
        }
        break;
    case 'u':
        Level->site[i][j].locchar = FLOOR;
        if (populate)
            make_minor_undead(i,j);
        break;
    case 'U':
        Level->site[i][j].locchar = FLOOR;
        if (populate)
            make_major_undead(i,j);
        break;
    case 'V':
        Level->site[i][j].showchar = WALL;
        Level->site[i][j].locchar = FLOOR;
        Level->site[i][j].p_locf = L_VAULT;
        if (populate)
            make_site_treasure(i,j,5);
        Level->site[i][j].aux = NOCITYMOVE;
        lset(i,j,SECRET);
        break;
    case '%':
        Level->site[i][j].showchar = WALL;
        Level->site[i][j].locchar = FLOOR;
        Level->site[i][j].p_locf = L_TRAP_SIREN;
        if (populate)
            make_site_treasure(i,j,5);
        Level->site[i][j].aux = NOCITYMOVE;
        lset(i,j,SECRET);
        break;
    case '$':
        Level->site[i][j].locchar = FLOOR;
        if (populate)
            make_site_treasure(i,j,5);
        break;
    case '2':
        Level->site[i][j].locchar = ALTAR;
        Level->site[i][j].p_locf = L_ALTAR;
        Level->site[i][j].aux = ODIN;
        break;
    case '3':
        Level->site[i][j].locchar = ALTAR;
        Level->site[i][j].p_locf = L_ALTAR;
        Level->site[i][j].aux = SET;
        break;
    case '4':
        Level->site[i][j].locchar = ALTAR;
        Level->site[i][j].p_locf = L_ALTAR;
        Level->site[i][j].aux = ATHENA;
        break;
    case '5':
        Level->site[i][j].locchar = ALTAR;
        Level->site[i][j].p_locf = L_ALTAR;
        Level->site[i][j].aux = HECATE;
        break;
    case '6':
        Level->site[i][j].locchar = ALTAR;
        Level->site[i][j].p_locf = L_ALTAR;
        Level->site[i][j].aux = DESTINY;
        break;
    case '^':
        Level->site[i][j].showchar = WALL;
        Level->site[i][j].locchar = FLOOR;
        Level->site[i][j].p_locf = TRAP_BASE+random_range(NUMTRAPS);
        lset(i,j,SECRET);
        break;
    case '"':
        Level->site[i][j].locchar = HEDGE;
        break;
    case '~':
        Level->site[i][j].locchar = WATER;
        Level->site[i][j].p_locf = L_WATER;
        break;
    case '=':
        Level->site[i][j].locchar = WATER;
        Level->site[i][j].p_locf = L_MAGIC_POOL;
        break;
    case '*':
        Level->site[i][j].locchar = WALL;
        Level->site[i][j].aux = 10;
        break;
    case '#':
        Level->site[i][j].locchar = WALL;
        Level->site[i][j].aux = 500;
        break;
    case 'T':/* currently meaningless in large city map. */
    case '>':  /* currently meaningless outside of maze.*/
    case '.':
        Level->site[i][j].locchar = FLOOR;
        break;
    case ',':
        Level->site[i][j].showchar = WALL;
        Level->site[i][j].locchar = FLOOR;
        Level->site[i][j].aux = NOCITYMOVE;
        lset(i,j,SECRET);
        break;
    case '-':
    case 'D': /* WDT: should all Ds be changed to -, or should D be given
					  * special treatment? */
        Level->site[i][j].locchar = CLOSED_DOOR;
        break;
    case '1':
        Level->site[i][j].locchar = STATUE;
        break;
    default:
        printf("\nOops... missed a case [%d,%d]: '%c' (%d)\n", i,j,site,site);
        morewait();
    }

    if (loc_statusp(i,j,SEEN)) {
        if (loc_statusp(i,j,SECRET))
            Level->site[i][j].showchar = WALL;
        else Level->site[i][j].showchar = Level->site[i][j].locchar;
    }
}
}
map_close(maze);
map_close(city);
City = Level;

       /* make all city monsters asleep, and shorten their wakeup range to 2 */
       /* to prevent players from being molested by vicious monsters on */
       /* the streets */
for(ml=Level->mlist; ml!=NULL; ml=ml->next) {
    m_status_reset(ml->m,AWAKE);
    ml->m->wakeup = 2;
}
initrand(E_RESTORE, 0);
}
Exemple #7
0
int main(int argc, char** argv)
{  
  if(argc^7){
    printf("Usage: ./osil bits seed N G Mu Chi\n");
    exit(1);
  }
  if ((sizeof(int) < 4)|| (sizeof(long int) < 8)){
    printf("Assumptions concerning bits are invalid: int has %d bits, unsigned long int has %d bits\n",
	   (int)(8*sizeof(int)), (int)(8*sizeof(unsigned long)));
    return 1;
  }
  L = atol(argv[1]);                     // bit length
  if (L > 32){
    printf("Can't have more thqan 32 bits\n");
    return 1;
  }
  int seed = atoi(argv[2]);
  N = (unsigned long)atoi(argv[3]);      // no. of individuals in finite population
  G = (unsigned long)atol(argv[4]);      // no. of generations
  Mu_n = atof(argv[5]);          
  Chi_n = atof(argv[6]);

  int i,j, n, m;
  double *d1, *d2, dst1, dst2;
  unsigned long *tmp_ptr;
  char fname[200];                       // file name
  FILE *fp;                              // data file pointer
  
  d1 = calloc(G, sizeof(double));
  d2 = calloc(G, sizeof(double));
  
  initrand(seed);
  setup();   
         
  init();                             // initializes memory for pop, M and Cr and also installs values for these  
  merge_sort(Pop[0], N);    
  // infinite population simulation   
  calc_px_from_finite_population(P0); // calculates haploids proportion using finite set
  P1 = g_w(G, P0, P1);
  display_p(P1);
  // find oscillating points for infinite population
  if( osc_points(P0, P1, P2, P3) ){     // if oscillation occurs
    {                                   // compute distance between finite population to oscillating points
      int a, b;  
      //finite population simulation
      for(i = 0; i < G; i++){           // evolve through G generations
	for(j = 0; j < N; j++){         // reproduce N offsprings      
	  a = rnd(N); b = rnd(N);
	  reproduce(a, b, j);           // randomly two parents chosen; will be proportional to proportion
	}
	merge_sort(Pop[0], N); 
	// calculate distance to oscillating points and write to file
	dst1 = dist_n(P2);               // distance to 1st oscillating point
	dst2 = dist_n(P3);               // distance to 2nd oscillating point
	d1[i] = dst1;
	d2[i] = dst2;
	// set new generation as parent generation for next generation
	tmp_ptr = Pop[0];
	Pop[0] = Pop[1];
	Pop[1] = tmp_ptr;		    
      }
    }
  }     
  deinit();        
  cleanup();
  
  sprintf(fname, "b%lug%lun%lu_osc.dat", L, G, N);
  if(!(fp = fopen(fname, "w"))){
    printf("%s could not be opened!! Error!!\n", fname);
    exit(2);
  }
   // write distances to file
   for(n = 0; n < G; n++){
    fprintf(fp, "%d  ", n);
    fprintf(fp, "%" PREC "lf  %" PREC "lf\n", d1[n], d2[n]);
   }
  fclose(fp);
  free(d1); free(d2);
  
  FILE *gp = popen ("gnuplot -persistent", "w"); // open gnuplot in persistent mode
  plot(gp, 0, fname, 3, "oscillation", "G", "d", 0, "" );
  fflush(gp);
  pclose(gp);
  
  return 0;
}
Exemple #8
0
int
main(int argc, char *argv[])
{
	char *progname;
	int fd;
	int c;
	extern char *optarg;
	unsigned nprocs = 0;
	unsigned procno;
	pid_t *pidarray=NULL;
	pid_t pid;
	pid_t wr_pid = 0;
	uchar_t *buf=NULL;
	unsigned int seed;
	int pagesize = sysconf(_SC_PAGE_SIZE);
	int alarmtime = 0;
	struct sigaction sa;
	unsigned i;
	int write_cnt;
	uchar_t data;
	int no_prob = 0;
	int wait_stat;
	time_t t;
#ifdef LARGE_FILE
	off64_t bytes_left;
#else /* LARGE_FILE */
	off_t bytes_left;
#endif /* LARGE_FILE */

	progname = *argv;
	tst_tmpdir();
	if (argc < 2) {
		(void)fprintf(stderr, "usage: %s %s\n", progname, usage);
		exit(1);
	}

	while ((c = getopt(argc, argv, "S:omdlrf:p:t:w:s:")) != -1) {
		switch (c) {
		case 'd':
			debug = 1;
			break;
		case 't':
			alarmtime = atoi(optarg) * 60;
			break;
		case 'p':
			nprocs = atoi(optarg);
			break;
		case 'l':
			leavefile = 1;
			break;
		case 's':
			sleeptime = atoi(optarg);
			if (sleeptime < 0) {
				(void)fprintf(stderr, "error: negative "
					"sleeptime\n");
                	        anyfail();
			}
			break;
		case 'w':
			growsize = atoi(optarg);
			if (growsize < 0) {
				(void)fprintf(stderr, "error: negative write "
					"size\n");
        	                anyfail();
			}
			break;
		case 'f':
#ifdef LARGE_FILE
			filesize = atoll(optarg);
#else /* LARGE_FILE */
			filesize = atoi(optarg);
#endif /* LARGE_FILE */
			if (filesize < 0) {
				(void)fprintf(stderr, "error: negative "
					"filesize\n");
                	        anyfail();
			}
			break;
		case 'r':
			randloops = 1;
			break;
		case 'm':
			dosync = 1;
			break;
		case 'o':
			do_offset = 1;
			break;
		case 'S':
#ifdef LARGE_FILE
			sparseoffset = atoll(optarg);
#else /* LARGE_FILE */
			sparseoffset = atoi(optarg);
#endif /* LARGE_FILE */
			if (sparseoffset % pagesize != 0) {
				fprintf(stderr, 
				   "sparseoffset must be pagesize multiple\n");
        	                anyfail();
			}
			break;
		default:
			(void)fprintf(stderr, "usage: %s %s\n", progname,
				usage);
			anyfail();
		}
	}

	if (nprocs > 255) {
		(void)fprintf(stderr, "invalid nprocs %d - (range 0-255)\n",
			nprocs);
                anyfail();
	}
	(void)time(&t);
	//(void)printf("%s: Started %s", argv[0], ctime(&t)); LTP Port

	(void)sprintf(filename, "%sout.%d", progname, getpid());
	seed = initrand();
	pattern = seed & 0xff;

	if (debug) {
#ifdef LARGE_FILE
		(void)printf("creating file <%s> with %Ld bytes, pattern %d\n", 
			filename, filesize, pattern);
#else /* LARGE_FILE */
		(void)printf("creating file <%s> with %ld bytes, pattern %d\n", 
			filename, filesize, pattern);
#endif /* LARGE_FILE */
		if (alarmtime)
			(void)printf("running for %d minutes\n", alarmtime/60);
		else
			(void)printf("running with no time limit\n");
	}

	/*
	 *  Plan for death by signal.  User may have specified
	 *  a time limit, in which case set an alarm and catch SIGALRM.
	 *  Also catch and cleanup with SIGINT, SIGQUIT, and SIGTERM.
	 */
	sa.sa_handler = finish;
	sa.sa_flags = 0;
	if (sigemptyset(&sa.sa_mask)) {
		perror("sigempty error");
		goto cleanup;
	}

	if (sigaction(SIGINT, &sa, 0) == -1) {
		perror("sigaction error SIGINT");
		goto cleanup;
	}
	if (alarmtime) {
		if (sigaction(SIGALRM, &sa, 0) == -1) {
			perror("sigaction error");
			goto cleanup;
		}
		(void)alarm(alarmtime);
	}
	/* If we get a SIGQUIT or SIGTERM, clean up and exit immediately. */
	sa.sa_handler = clean_up_file;
	if (sigaction(SIGQUIT, &sa, 0) == -1) {
		perror("sigaction error SIGQUIT");
		goto cleanup;
	}
	if (sigaction(SIGTERM, &sa, 0) == -1) {
		perror("sigaction error SIGTERM");
		goto cleanup;
	}

#ifdef LARGE_FILE
	if ((fd = open64(filename, O_CREAT|O_TRUNC|O_RDWR, 0664)) == -1) {
#else /* LARGE_FILE */
	if ((fd = open(filename, O_CREAT|O_TRUNC|O_RDWR, 0664)) == -1) {
#endif /* LARGE_FILE */
		perror("open error");
                anyfail();
	}

	if ((buf = (uchar_t *)malloc(pagesize+growsize)) == NULL
	    || (pidarray = (pid_t *)malloc(nprocs*sizeof(pid_t))) == NULL) {
		perror("malloc error");
                anyfail();
	}

	for (i = 0; i < nprocs; i++)
		*(pidarray+i) = 0;

	for (i = 0, data = 0; i < pagesize; i++) {
		*(buf+i) = (data + pattern) & 0xff;
		if (++data == nprocs)
			data = 0;
	}
	for (data = 0; i < pagesize+growsize; i++) {
		*(buf+i) = (data + pattern) & 0xff;
		if (++data == nprocs)
			data = 0;
	}

#ifdef LARGE_FILE
	if (lseek64(fd, sparseoffset, SEEK_SET) < 0) {
#else /* LARGE_FILE */
	if (lseek(fd, sparseoffset, SEEK_SET) < 0) {
#endif /* LARGE_FILE */
		perror("lseek");
               anyfail();
	}

	for (bytes_left = filesize; bytes_left; bytes_left -= c) {
		write_cnt = min(pagesize, bytes_left);
		if ((c = write(fd, (char *)buf, write_cnt)) != write_cnt) {
			if (c == -1) {
				perror("write error");
			} else {
				(void)fprintf(stderr, "write: wrote %d of %d "
					"bytes\n", c, write_cnt);
			}
			(void)close(fd);
			(void)unlink(filename);
			anyfail();
		}
	}

	(void)close(fd);

	/*
	 *  Fork off mmap children.
	 */
	for (procno = 0; procno < nprocs; procno++) {
		switch (pid = fork()) {

		case -1:
			perror("fork error");
			goto cleanup;

		case 0:
			child_mapper(filename, procno, nprocs);
			exit(0);

		default:
			pidarray[procno] = pid;
		}
	}

	/*
	 *  Now fork off an additional process to continually
	 *  write to (and grow) the file.
	 */
	if ((wr_pid = fork()) == -1) {
		perror("fork error");
		goto cleanup;
	} else if (wr_pid == 0) {	/* child */
		child_writer(filename, buf);
		exit(0);
	}

	/*
	 *  Now wait for children and refork them as needed.
	 */
	
	while (!finished) {
		pid = wait(&wait_stat);
		/*
		 *  Block signals while processing child exit.
		 */

		if (sighold(SIGALRM) || sighold(SIGINT)) {
			perror("sighold error");
			goto cleanup;
		}

		if (pid != -1) {
			/*
			 *  Check exit status, then refork with the
			 *  appropriate procno.
			 */
			if (!WIFEXITED(wait_stat) 
			    || WEXITSTATUS(wait_stat) != 0) {
				(void)fprintf(stderr, "child exit with err "
					"<x%x>\n", wait_stat);
				goto cleanup;
			}
			for (i = 0; i < nprocs; i++)
				if (pid == pidarray[i])
					break;
			if (i == nprocs) {
				if (pid == wr_pid) {
					(void)fprintf(stderr, 
					"writer child unexpected exit <x%x>\n",
						wait_stat);
					wr_pid = 0;
				} else
					(void)fprintf(stderr, "unknown child "
						"pid %d, <x%x>\n",
						pid, wait_stat);
				goto cleanup;
			}

			if ((pid = fork()) == -1) {
				perror("fork error");
				pidarray[i] = 0;
				goto cleanup;
			} else if (pid == 0) {		/* child */
				child_mapper(filename, i, nprocs);
				exit(0);
			} else
				pidarray[i] = pid;
		} else {
			/*
			 *  wait returned an error.  If EINTR, then
			 *  normal finish, else it's an unexpected
			 *  error...
			 */
			if (errno != EINTR || !finished) {
				perror("unexpected wait error");
				goto cleanup;
			}
		}
		if (sigrelse(SIGALRM) || sigrelse(SIGINT)) {
			perror("sigrelse error");
			goto cleanup;
		}
	}
	
	/*
	 *  Finished!  Check the file for sanity, then kill all
	 *  the children and done!.
	 */

	(void)alarm(0);
	no_prob = 1;

cleanup:
	for (i = 0; i < nprocs; i++)
		(void)kill(pidarray[i], SIGKILL);
	(void)kill(wr_pid, SIGKILL);

	while (wait(&wait_stat) != -1 || errno != ECHILD)
		continue;

	if (no_prob) {		/* only check file if no errors */
		if (!fileokay(filename, buf)) {
			(void)fprintf(stderr, "file data incorrect!\n");
			(void)printf("  leaving file <%s>\n", filename);
                        anyfail();

		} else {
			(void)printf("file data okay\n");
			if (!leavefile)
				(void)unlink(filename);
		}
	} else
		(void)printf("  leaving file <%s>\n", filename);
	
	(void)time(&t);
//	(void)printf("%s: Finished %s", argv[0], ctime(&t)); LTP Port
	ok_exit();
	return 0;
}


/*
 *  Child process that reads/writes map.  The child stats the file
 *  to determine the size, maps the size of the file, then reads/writes
 *  its own locations on random pages of the map (its locations being
 *  determined based on nprocs & procno).  After a specific number of
 *  iterations, it exits.
 */
void
child_mapper(char *file, unsigned procno, unsigned nprocs)
{
#ifdef LARGE_FILE
	struct stat64 statbuf;
	off64_t filesize;
	off64_t offset;
#else /* LARGE_FILE */
	struct stat statbuf;
	off_t filesize;
	off_t offset;
#endif /* LARGE_FILE */
	size_t validsize;
	size_t mapsize;
	caddr_t maddr, paddr;
	int fd;
	int pagesize = sysconf(_SC_PAGE_SIZE);
	unsigned randpage;
	unsigned int seed;
	unsigned loopcnt;
	unsigned nloops;
	unsigned mappages; 
	unsigned mapflags;
	unsigned i;

	mapflags = MAP_SHARED;

	seed = initrand();		/* initialize random seed */


#ifdef LARGE_FILE
	if ((fd = open64(file, O_RDWR)) == -1) {
#else /* LARGE_FILE */
	if ((fd = open(file, O_RDWR)) == -1) {
#endif /* LARGE_FILE */
		perror("open error");
                anyfail();
	}

#ifdef LARGE_FILE
	if (fstat64(fd, &statbuf) == -1) {
#else /* LARGE_FILE */
	if (fstat(fd, &statbuf) == -1) {
#endif /* LARGE_FILE */
		perror("stat error");
                anyfail();
	}
	filesize = statbuf.st_size;

	if (statbuf.st_size - sparseoffset > SIZE_MAX) {
		fprintf(stderr, "size_t overflow when setting up map\n");
                anyfail();
	}
	mapsize = (size_t)(statbuf.st_size - sparseoffset);
	mappages = roundup(mapsize, pagesize) / pagesize;
	offset = sparseoffset;
	if (do_offset) {
		int pageoffset = lrand48() % mappages;
		int byteoffset = pageoffset * pagesize;
		offset += byteoffset;
		mapsize -= byteoffset;
		mappages -= pageoffset;
	}

#ifdef LARGE_FILE
	if ((maddr = mmap64(0, mapsize, PROT_READ|PROT_WRITE, 
			mapflags, fd, offset)) == (caddr_t)-1) {
#else /* LARGE_FILE */
	if ((maddr = mmap(0, mapsize, PROT_READ|PROT_WRITE, 
			mapflags, fd, offset)) == (caddr_t)-1) {
#endif /* LARGE_FILE */
		perror("mmap error");
                anyfail();
	}

	(void)close(fd);

	nloops = (randloops) ? (lrand48() % MAXLOOPS) : MAXLOOPS;

	if (debug) {
#ifdef LARGE_FILE
		(void)printf("child %d (pid %ld): seed %d, fsize %Ld, "
			"mapsize %d, off %Ld, loop %d\n",
			procno, getpid(), seed, filesize, mapsize,
			offset/pagesize, nloops);
#else /* LARGE_FILE */
		(void)printf("child %d (pid %d): seed %d, fsize %ld, "
			"mapsize %ld, off %ld, loop %d\n",
			procno, getpid(), seed, filesize, (long)mapsize,
			offset/pagesize, nloops);
#endif /* LARGE_FILE */
	}

	/*
	 *  Now loop read/writing random pages.
	 */
	for (loopcnt = 0; loopcnt < nloops; loopcnt++) {
		randpage = lrand48() % mappages;
		paddr = maddr + (randpage * pagesize);	 /* page address */

		if (randpage < mappages - 1
		    || !(mapsize % pagesize))
			validsize = pagesize;
		else
			validsize = mapsize % pagesize;

		/*
		 * Because one child is mapping file in extend mode,
		 * it may be padded with zeros at end.  So we can't
		 * do an exact check -- accept known pattern OR zeros.
		 */
		for (i = procno; i < validsize; i += nprocs) {
			if (*((unsigned char *)(paddr+i)) 
			    != ((procno + pattern) & 0xff)
			    && *((unsigned char *)(paddr+i)) != 0) {
				(void)fprintf(stderr, "child %d: invalid data "
				"<x%x>", procno, *((unsigned char *)(paddr+i)));
				(void)fprintf(stderr, " at pg %d off %d, exp "
					"<x%x>\n", randpage, i,
					(procno+pattern)&0xff);
                        anyfail();
			}
			/*
			 *  Now write it.
			 */

			*(paddr+i) = (procno + pattern) & 0xff;
		}
	}
	if (dosync) {
		/*
		 * Exercise msync() as well!
		 */
		randpage = lrand48() % mappages;
		paddr = maddr + (randpage * pagesize);	 /* page address */
		if (msync(paddr, (mappages - randpage)*pagesize, 
		    MS_SYNC) == -1) {
			perror("msync error");
                        anyfail();
		}
	}

	exit(0);
}

/*
 *  child_writer
 * 	The child process that continually (and slowly!!) grows
 *	the file.  The purpose of this is to exercise the code
 *	supporting mapping of fragments.  The map children are 
 *	constantly reforking and will pick up the map changes, etc.
 *	This process executes until signalled (i.e. has no exit!)
 *	unless error.	
 */
void
child_writer(char *file, uchar_t *buf)	/* buf already set up in main */
{
	int fd;
#ifdef LARGE_FILE
	struct stat64 statbuf;
	off64_t off;
#else /* LARGE_FILE */
	struct stat statbuf;
	off_t off;
#endif /* LARGE_FILE */
	int pagesize = sysconf(_SC_PAGE_SIZE);
	uchar_t *p;
	int cnt;

#ifdef LARGE_FILE
	if ((fd = open64(file, O_RDWR)) == -1) {
#else /* LARGE_FILE */
	if ((fd = open(file, O_RDWR)) == -1) {
#endif /* LARGE_FILE */
		perror("open error");
                anyfail();
	}

#ifdef LARGE_FILE
	if ((off = lseek64(fd, 0, SEEK_END)) == -1) {
#else /* LARGE_FILE */
	if ((off = lseek(fd, 0, SEEK_END)) == -1) {
#endif /* LARGE_FILE */
		perror("lseek error");
                anyfail();
	}


	for (;;) {
#ifdef LARGE_FILE
		if (fstat64(fd, &statbuf) == -1) {
#else /* LARGE_FILE */
		if (fstat(fd, &statbuf) == -1) {
#endif /* LARGE_FILE */
			perror("fstat error");
                        anyfail();
		}
#ifdef LARGE_FILE
		if (debug)
			(void)printf("writer %d bytes at off %Ld, size %Ld\n", 
				growsize, off, statbuf.st_size); 
#else /* LARGE_FILE */
		if (debug)
			(void)printf("writer %d bytes at off %ld, size %ld\n", 
				growsize, off, statbuf.st_size); 
#endif /* LARGE_FILE */

		/*
		 *  Write some number of bytes, then sleep some
		 *  number of seconds...
		 *  Need to keep track of our offset so write the
		 *  right bytes.
		 */

		p = buf + (off % pagesize);

		if ((cnt = write(fd, p, growsize)) != growsize) {
			if (cnt == -1)
				perror("write error");
			else
				(void)fprintf(stderr, "wrote %d of %d bytes\n",
					cnt, growsize);
                        anyfail();
		}

		off += growsize;

		(void)sleep(sleeptime);
		if (dosync) {
			if (fsync(fd) == -1) {
				perror("fsync error");
                                anyfail();
			}
		}
	}
}


/*
 *  Make sure file has all the correct data.

 */
int
fileokay(char *file, uchar_t *expbuf)
{
#ifdef LARGE_FILE
	struct stat64 statbuf;
#else /* LARGE_FILE */
	struct stat statbuf;
#endif /* LARGE_FILE */
	size_t mapsize;
	uchar_t *readbuf;
	unsigned mappages;
	unsigned pagesize = sysconf(_SC_PAGE_SIZE);
	int fd;
	int cnt;
	unsigned i, j;

#ifdef LARGE_FILE
	if ((fd = open64(file, O_RDONLY)) == -1) {
#else /* LARGE_FILE */
	if ((fd = open(file, O_RDONLY)) == -1) {
#endif /* LARGE_FILE */
		perror("open error");
                anyfail();
	}
#ifdef LARGE_FILE
	if (fstat64(fd, &statbuf) == -1) {
#else /* LARGE_FILE */
	if (fstat(fd, &statbuf) == -1) {
#endif /* LARGE_FILE */
		perror("stat error");
                anyfail();
	}
#ifdef LARGE_FILE
	if (lseek64(fd, sparseoffset, SEEK_SET) < 0) {
#else /* LARGE_FILE */
	if (lseek(fd, sparseoffset, SEEK_SET) < 0) {
#endif /* LARGE_FILE */
		perror("lseek");
		exit(1);
	}

	readbuf = (uchar_t *)malloc(pagesize);

	if (statbuf.st_size - sparseoffset > SIZE_MAX) {
		fprintf(stderr, "size_t overflow when setting up map\n");
		exit(1);
	}
	mapsize = (size_t)(statbuf.st_size - sparseoffset);
	mappages = roundup(mapsize, pagesize) / pagesize;

	for (i = 0; i < mappages; i++) {
		cnt = read(fd, (char *)readbuf, pagesize);
		if (cnt == -1) {
			perror("read error");
			return(0);	
		} else if (cnt != pagesize) {
			/*
			 *  Okay if at last page in file... 
			 */
			if ((i * pagesize) + cnt != mapsize) {
				(void)fprintf(stderr, "read %d of %ld bytes\n",
					(i*pagesize)+cnt, (long)mapsize);
				return(0);
			}
		}
		/*
		 *  Compare read bytes of data.
		 *  May have zeros from map extend...
		 */
		for (j = 0; j < cnt; j++) {
			if (expbuf[j] != readbuf[j] && readbuf[j] != 0) {
				(void)fprintf(stderr, 
					"read bad data: exp %c got %c",
					expbuf[j], readbuf[j]);
#ifdef LARGE_FILE
				(void)fprintf(stderr, ", pg %d off %d, "
					"(fsize %Ld)\n", i, j, statbuf.st_size);
#else /* LARGE_FILE */
				(void)fprintf(stderr, ", pg %d off %d, "
					"(fsize %ld)\n", i, j, statbuf.st_size);
#endif /* LARGE_FILE */
				return(0);
			}
		}
	}
					
	return(1);
}

/*ARGSUSED*/
void
finish(int sig)
{
	finished++;
	/* finish nicely and check the file contents */
}

/*ARGSUSED*/
void
clean_up_file(int sig)
{
	if (!leavefile)
		(void)unlink(filename);
	exit(1);
}

unsigned int
initrand(void)
{
	unsigned int seed;

	/*
	 *  Initialize random seed...  Got this from a test written
	 *  by scooter:
	 *	Use srand/rand to diffuse the information from the
	 *	time and pid.  If you start several processes, then
	 *	the time and pid information don't provide much
	 *	variation.
	 */
	srand((unsigned int)getpid());
	seed = rand();
	srand((unsigned int)time((time_t *)0));
	seed = (seed ^ rand()) % 100000;
	srand48((long int)seed);
	return (seed);
}


/*****  LTP Port        *****/
void ok_exit()
{
        tst_resm(TPASS, "Test passed\n");
	tst_rmdir();
	tst_exit();
}


int anyfail()
{
  tst_resm(TFAIL, "Test failed\n");
  tst_rmdir();
  tst_exit();
  return(0);
}
Exemple #9
0
int main(int argc, char *argv[])
{
  int continuing = 0;
  int count;
  int scores_only = 0;
  int i;

#ifndef NOGETOPT
  while(( i= getopt( argc, argv, "dsh")) != -1)
  {
     switch (i)
     {
       case 'd':
#ifdef DEBUG
         DG_debug_flag++;
#endif
         break;
       case 's':
         scores_only = 1;
         break;
       case 'h':
#ifdef DEBUG
         printf("Usage: omega [-shd] [savefile]\n");
#else
         printf("Usage: omega [-sh] [savefile]\n");
#endif
         printf("Options:\n");
         printf("  -s  Display high score list\n");
         printf("  -h  Display this message\n");
#ifdef DEBUG
         printf("  -d  Enable debug mode\n");
#endif
         exit(0);
         break;
       case '?':
         /* error parsing args... ignore? */
         printf("'%c' is an invalid option, ignoring\n", optopt );
         break;
     }
  }

  if (optind >= argc ) {
    /* no save file given */
#if defined( BSD ) || defined( SYSV )
    sprintf( SaveFileName, "Omega%d", getuid() );
#else
    strcpy( SaveFileName,"Omega");
#endif
  } else {
    /* savefile given */
    continuing = 1;
    strcpy(SaveFileName,argv[optind]);
  }

#else 
  /* alternate code for people who don't support getopt() -- no enhancement */
  if (argc ==2) {
    strcpy( SaveFileName, argv[1]);
    continuing = 1;
  } else {
    strcpy( SaveFileName,"Omega");
  }
#endif

  /* always catch ^c and hang-up signals */

#ifdef SIGINT
  signal(SIGINT,signalquit);
#endif
#ifdef SIGHUP
  signal(SIGHUP,signalsave);
#endif

#ifndef MSDOS
  if (CATCH_SIGNALS) {
    signal(SIGQUIT,signalexit);
    signal(SIGILL,signalexit);
#ifdef DEBUG
    if( DG_debug_flag ) {
#endif
    signal(SIGTRAP,signalexit);
    signal(SIGFPE,signalexit);
    signal(SIGSEGV,signalexit);
#ifdef DEBUG
    }
#endif
#ifdef SIGIOT
    signal(SIGIOT,signalexit);
#endif
#ifdef SIGABRT
    signal(SIGABRT,signalexit);
#endif
#ifdef SIGEMT
    signal(SIGEMT,signalexit);
#endif
#ifdef SIGBUS
    signal(SIGBUS,signalexit);
#endif
#ifdef SIGSYS
    signal(SIGSYS,signalexit);
#endif
    }
#endif

#ifndef FIXED_OMEGALIB
  if (!(Omegalib = getenv("OMEGALIB")))
#endif
    Omegalib = OMEGALIB;

  /* if filecheck is 0, some necessary data files are missing */
  if (filecheck() == 0) exit(0);

  /* all kinds of initialization */
  init_perms();
  initgraf();
#ifndef MSDOS_SUPPORTED_ANTIQUE
  initdirs();
#endif
  initrand(E_RANDOM, 0);
  initspells();

#ifdef DEBUG
  /* initialize debug log file */
  DG_debug_log = fopen( "/tmp/omega_dbg_log", "a" );
  assert( DG_debug_log ); /* WDT :) */
  setvbuf( DG_debug_log, NULL, _IOLBF, 0);
  fprintf(DG_debug_log, "##############  new game started ##############\n");
#endif

  for (count = 0; count < STRING_BUFFER_SIZE; count++)
    strcpy(Stringbuffer[count],"<nothing>");

#ifdef SAVE_LEVELS
  msdos_init();
#endif

  omega_title();
  showscores();

  if (scores_only ) {
    endgraf();
    exit(0);
  }

  /* game restore attempts to restore game if there is an argument */
  if (continuing) 
  {
     game_restore(SaveFileName);
     mprint("Your adventure continues....");
  }
  else
  {
    /* monsters initialized in game_restore if game is being restored */  
    /* items initialized in game_restore if game is being restored */
    inititem(TRUE);
    Date = random_range(360);
    Phase = random_range(24);
#ifdef NEW_BANK
    bank_init();
#else
    strcpy(Password,"");
#endif
    continuing = initplayer(); /* RM: 04-19-2000 loading patch */
  }
  if (!continuing)
  {
    init_world();  /* RM: 04-19-2000 loading patch */
    mprint("'?' for help or commandlist, 'Q' to quit.");
  }

  timeprint();
  calc_melee();
  if (Current_Environment != E_COUNTRYSIDE)
    showroom(Level->site[Player.x][Player.y].roomnumber);
  else
    terrain_check(FALSE);
  
  if (optionp(SHOW_COLOUR))
    colour_on();
  else
    colour_off();

  screencheck(Player.x,Player.y);

 /* game cycle */
  if (!continuing)
    time_clock(TRUE);
  while (TRUE) {
    if (Current_Environment == E_COUNTRYSIDE)
      p_country_process();
    else time_clock(FALSE);
  }
}
Exemple #10
0
void CRex::vInitialize( int iGenerationNum, int iGenNum, int iGenVectorData, int iParentNumberData, int iChildrenNumberData )
{
	int i;
	CRexException cre;

	// 親の生成数を設定します。
	iParentNumber = iParentNumberData > iGenNum ? iGenNum : iParentNumberData;

	// 子供の生成数を設定します。
	iChildrenNumber = iChildrenNumberData;

	// 実数値GAの初期化を実行します。
	CRealCodedGa::vInitialize( iGenerationNum, iGenNum, iGenVectorData );

	try
	{
		// 親選択用配列です。
		piParentLoc = new int[iGenNum];
		if( piParentLoc == NULL )
		{
			cre.SetErrorInfo( REX_MEMORY_ALLOCATE_ERROR, "vInitialize", "CRex", "メモリ確保に失敗しました。", __LINE__ );
			throw( cre );
		}
		// 子供のデータを作成します。
		pplfChildren = new double*[iChildrenNumber];
		if( pplfChildren == NULL )
		{
			cre.SetErrorInfo( REX_MEMORY_ALLOCATE_ERROR, "vInitialize", "CRex", "メモリ確保に失敗しました。", __LINE__ );
			throw( cre );
		}
		for( i = 0;i < iChildrenNumber; i++ )
		{
			pplfChildren[i] = new double[iGenVector];
			if( pplfChildren[i] == NULL )
			{
				cre.SetErrorInfo( REX_MEMORY_ALLOCATE_ERROR, "vInitialize", "CRex", "メモリ確保に失敗しました。", __LINE__ );
				throw( cre );
			}
		}
		// REX計算用ベクトルデータ一時保存変数です。
		plfTempVector = new double[iGenVector];
		if( plfTempVector == NULL )
		{
			cre.SetErrorInfo( REX_MEMORY_ALLOCATE_ERROR, "vInitialize", "CRex", "メモリ確保に失敗しました。", __LINE__ );
			throw( cre );
		}
		// 重心の計算結果を保持します。
		plfCentroid = new double[iGenVector];
		if( plfCentroid == NULL )
		{
			cre.SetErrorInfo( REX_MEMORY_ALLOCATE_ERROR, "vInitialize", "CRex", "メモリ確保に失敗しました。", __LINE__ );
			throw( cre );
		}
		plfChildVector = new double[iGenVector];
		if( plfChildVector == NULL )
		{
			cre.SetErrorInfo( REX_MEMORY_ALLOCATE_ERROR, "vInitialize", "CRex", "メモリ確保に失敗しました。", __LINE__ );
			throw( cre );
		}
		plfNormalizeRand = new double[iParentNumber];
		if( plfNormalizeRand == NULL )
		{
			cre.SetErrorInfo( REX_MEMORY_ALLOCATE_ERROR, "vInitialize", "CRex", "メモリ確保に失敗しました。", __LINE__ );
			throw( cre );
		}
		plfChildrenCentroid = new double[iGenVector];
		if( plfChildrenCentroid == NULL )
		{
			cre.SetErrorInfo( REX_MEMORY_ALLOCATE_ERROR, "vInitialize", "CRex", "メモリ確保に失敗しました。", __LINE__ );
			throw( cre );
		}
		plfUpperEvalChildrenCentroid = new double[iGenVector];
		if( plfUpperEvalChildrenCentroid == NULL )
		{
			cre.SetErrorInfo( REX_MEMORY_ALLOCATE_ERROR, "vInitialize", "CRex", "メモリ確保に失敗しました。", __LINE__ );
			throw( cre );
		}
		plfCentroidSteep = new double[iGenVector];
		if( plfCentroidSteep == NULL )
		{
			cre.SetErrorInfo( REX_MEMORY_ALLOCATE_ERROR, "vInitialize", "CRex", "メモリ確保に失敗しました。", __LINE__ );
			throw( cre );
		}

		for( i = 0;i < iChildrenNumber; i++ )
		{
			memset( pplfChildren[i], 0, iGenVector*sizeof(double) );
		}
		for( i = 0;i < iGenVector; i++ )
		{
			plfCentroid[i] = 0.0;
			plfChildVector[i] = 0.0;
			plfTempVector[i] = 0.0;
			plfUpperEvalChildrenCentroid[i] = 0.0;
			plfChildrenCentroid[i] = 0.0;
			plfCentroidSteep[i] = 0.0;
		}
		for( i = 0;i < iParentNumber; i++ )
		{
			plfNormalizeRand[i] = 0.0;
			piParentLoc[i] = i;
		}
		for( i = 0;i < iGenNum; i++ )
		{
			piParentLoc[i] = i;
		}

		initrand( (unsigned long)time(NULL) );
		initrnd();
	}
	catch( std::bad_alloc ba )
	{
		cre.SetErrorInfo( REX_MEMORY_ALLOCATE_ERROR, "vInitialize", "CRex", "メモリ確保に失敗しました。", __LINE__ );
		throw( cre );
	}
	catch( ... )
	{
		cre.SetErrorInfo( REX_ARRAY_INDEX_ERROR, "vInitialize", "CRex", "配列範囲外を参照しました。", __LINE__ );
		throw( cre );
	}
}
DocumentsBuilder::DocumentsBuilder()
{
	initrand();
	for (int i = 0; i < AGENT_COUNT; i++)
	{
		int len = randint(100);
		char* agent = (char*) malloc(len);
		agents[i] = randstr(agent, len);
	}

	for (int i = 0; i < PRODUCT_COUNT; i++)
	{
		int len = randint(20, 200);
		char* name = (char*) malloc(len);
		product_names[i] = randstr(name, len);
	}
	static char* domains[8] = { "com", "net", "org", "us", "biz", "vn", "info", "edu" };

	for (int i = 0; i < URL_COUNT; i++)
	{
		if (rand() < (RAND_MAX / 10000)) //0.01%
		{
			urls[i] = "http://www.ouzo.com/abcdef";
			//printf(urls[i]);
		}
		else
		{
			int len = randint(4, 20);
			char* name = (char*) malloc(len);

			randstr(name, len, RAND_STR_LOWER_CASE_LETTERS);
			int dom = randint(8);
			char* url = (char*) malloc(len + strlen(domains[dom]) + strlen("http://") + 1);
			sprintf(url, "http://%s.%s", name, domains[dom]);
			free(name);
			urls[i] = url;
		}
		//printf("%s\n", url);
	}

	for (int i = 0; i < VARIABLE_COUNT; i++)
	{
		int len = randint(2, 8);
		char* name = (char*) malloc(len);

		randstr(name, len, RAND_STR_LOWER_CASE_LETTERS);
		variables[i] = name;
		//printf("%s\n", url);
	}

	for (int i = 0; i < 100000; i++)
	{
		int len = randint(10, 25);
		char* name = (char*) malloc(len);

		randstr(name, len, RAND_STR_LOWER_CASE_LETTERS);
		new_country[i] = name;
		//printf("%s\n", url);
	}

}
Exemple #12
0
void change_level (char fromlevel, char tolevel, char rewrite_level)
{
    struct level * thislevel = NULL;
    Player.sx = -1;
    Player.sy = -1; /* sanctuary effect dispelled */

    thislevel = findlevel(Dungeon, tolevel);
    deepest[Current_Environment] = max(deepest[Current_Environment], tolevel);
    if (!thislevel)
    {
        thislevel = (level*) checkmalloc(sizeof(levtype));
        clear_level(thislevel);
        Level = thislevel;
        Level->next = Dungeon;
        Dungeon = Level;
    }

    Level = thislevel;
    if ((!Level->generated) || rewrite_level)
    {
        initrand(Current_Environment, tolevel);
        Level->environment = Current_Environment;
        Level->depth = tolevel;
        Level->generated = true;

        switch (Current_Environment)
        {
        case E_CAVES:
            Level->level_width = CAVES_WIDTH;
            Level->level_length = CAVES_LENGTH;
            if ((0 == random_range(4)) && (tolevel < MaxDungeonLevels))
                room_level();
            else
                cavern_level();
            break;

        case E_SEWERS:
            Level->level_width = SEWERS_WIDTH;
            Level->level_length = SEWERS_LENGTH;
            if ((0 == random_range(4)) && (tolevel < MaxDungeonLevels))
                room_level();
            else
                sewer_level();
            break;

        case E_CASTLE:
            Level->level_width = CASTLE_WIDTH;
            Level->level_length = CASTLE_LENGTH;
            room_level();
            break;

        case E_PALACE: /* PGM TODO */
            Level->level_width = PALACE_WIDTH;
            Level->level_length = PALACE_LENGTH;
            room_level();
            break;

        case E_ASTRAL:
            Level->level_width = ASTRAL_WIDTH;
            Level->level_length = ASTRAL_LENGTH;
            maze_level();
            break;

        case E_VOLCANO:
            Level->level_width = VOLCANO_WIDTH;
            Level->level_length = VOLCANO_LENGTH;
            switch (random_range(3))
            {
            case 0:
                cavern_level();
                break;
            case 1:
                room_level();
                break;
            case 2:
                maze_level();
                break;
            }
            break;

        default:
            print3("This dungeon not implemented!");
            assert(false);
            break;
        }

        install_traps();
        install_specials();
        make_stairs(fromlevel);
        make_stairs(fromlevel);
        initrand(E_RESTORE, 0);
        populate_level(Current_Environment);
        stock_level();
    }

    find_stairs(fromlevel, tolevel);
    ScreenOffset = Player.y - (ScreenLength/2);
    show_screen();
    screencheck(Player.x,Player.y);
    drawvision(Player.x,Player.y);

    /* synchronize with player on level change */
    Player.click = (Tick+1)%60;
    roomcheck();
}
Exemple #13
0
int main(int argc, char **argv)
{
#if DEBUG
  feenableexcept(FE_DIVBYZERO| FE_INVALID|FE_OVERFLOW); // enable exceptions
#endif
  if(argc ^ 2){
    printf("Usage: ./sa sa.config\n");
    exit(1);
  }
  if(read_config(argv[1])){           // read config
    printf("READDATA: Can't process %s \n", argv[1]);
    return 1;
  }  
  T = T+SKIP;               // increase T by SKIP to go from 0 to T all the way in time units
  
  // precomputing  
  I_Gamma = 1.0/Gamma;
  I_Alpha = 1.0/Alpha;    
  Bo = B;    
  X0_Be = pow(X0, Beta);
  GaBe  = Gamma * Beta;

  // event probabilites scaling by G;
  PE[0] = PE[0]*(double)G;
  PE[1] = PE[1]*(double)G;
  PE[2] = PE[2]*(double)G;
  
  initrand(Seed);
  init();          // note: method is in init.c  // allocate memory at initial  
  
  int i, j, ev, k = 0; // m;
  unsigned long seed;
  double dt, ct, tt;      // tt: time of simulation; dt: delta time after which next event occurs; ct: counter time to check with skip time for stat calculation
  time_t now;   
 
  for( i = 0; i < Runs; i++){
    tt = 0.0, ct = 0.0;
    k = 0; //m = 0;
    if(Seed == 0){      
      now = time(0);
      seed = ((unsigned long)now);  
      seed = 1454011037;
      initrand(seed);
      printf("\n run: %d rand seed: %lu\n",i+1, seed);
    }
    set_init_xrvpi();   // sets initial strategies vector, roles, valuations and payoffs       
     
    calc_stat(0, i);
    
    for( j = 0; j < N; j++) printf("%.4lf  ", V[0][j]); printf("\n");
    
    // Gillespie's stochastic simulation 
    while(tt < T){     
      // calc lambda; lambda = summation of P[j]s
      for(Lambda = 0, j = EVENTS; j--;)
	Lambda += PE[j];
      // select time for next event
      dt = randexp(Lambda); //printf("dt: %.4lf\n", dt);
      // select next event
      ev = select_event();
      // play the event      
      play_event(ev);
      // update time
      tt += dt;
      // calc stat
      ct += dt;
      if(ct >= SKIP){
        calc_stat(++k, i); // calculates all the stats	
	ct = 0.0;
      }
      // update events associated probabilites if necessary
    }
#if ALLDATAFILE
    calc_stat(-1, -1);    // free file pointers for individual run data files
#if !CLUSTER
    plotallIndividualRun(i, 0);      // note: method is in dataplot.c  
#if GRAPHS
    plotallIndividualRun(i, 1);      // note: method is in dataplot.c
#endif
#endif
    // write traits of final state
    {
      int m, n;
      char tstr[200], str[100];
      sprintf(str, "traits%d.dat", i);
      sprintf(str, "traits%d.dat", i); prep_file(tstr, str);
      FILE *fp = fopen(tstr, "w");
      for(m = 0; m < G; m++){
	for( n = 0; n < GS[m]; n++){
	  fprintf(fp, "%.4lf %.4lf    ", dxi[m][n], dsi[m][n]);
	}
	fprintf(fp, "\n");
      }
      fclose(fp);
    }
#if PUNISH
#if DISP_MATRIX
    plotTraits(i, 0);   // note: method is in dataplot.c
#endif
#if GRAPHS
    plotTraits(i, 1);   // note: method is in dataplot.c
#endif
#endif
#endif
  }  
  // write effort and payoff data
  writefile_effort_fertility();              // note: method is in dataplot.c
  writefile_threshold_aggressiveness();      // note: method is in dataplot.c
  // plot data with graphics using gnuplot
  if(!CLUSTER){    
    plotall(0);                              // note: method is in dataplot.c
#if GRAPHS
    plotall(1);                              // note: method is in dataplot.c
#endif
  }
#if PUNISH
#if DISP_MATRIX
  displayMatrix();                           
#endif  
#endif
  
  cleanup();                                 // note: method is in init.c
  return 0;
}
Exemple #14
0
/* loads the house level into Level*/
void load_house(int kind, int populate)
{
  map *home;
  int i,j;
  char site;
  int stops;
  
  TempLevel = Level;
  initrand(Current_Environment, Player.x + Player.y + hour()*10);
  if (ok_to_free(TempLevel)) {
#ifndef SAVE_LEVELS
    free_level(TempLevel);
#endif
    TempLevel = NULL;
  }
#ifndef SAVE_LEVELS
  Level = ((plv) checkmalloc(sizeof(levtype)));
#else
  msdos_changelevel(TempLevel,0,-1);
  Level = &TheLevel;
#endif
  clear_level(Level);
  switch(kind) {
  case E_HOUSE:
    home = map_open(MAP_house);
    break;
  case E_MANSION:
    home = map_open(MAP_mansion);
    break;
  default:
  case E_HOVEL:
    home = map_open(MAP_hovel);
    break;
  }
  Level->level_width=map_getWidth(home);
  Level->level_length=map_getLength(home);
  map_setLevel(home, 0);
  
  stops = 0;
  for(j=0;j<Level->level_length;j++) {
    for(i=0;i<Level->level_width;i++) {
      if (kind == E_HOVEL) Level->site[i][j].lstatus = SEEN;
      else Level->site[i][j].lstatus = 0;
      Level->site[i][j].roomnumber = RS_CORRIDOR;
      Level->site[i][j].p_locf = L_NO_OP;
      site = map_getSiteChar(home,i,j);
      switch(site) {
      case 'N':
	Level->site[i][j].locchar = FLOOR;
	Level->site[i][j].roomnumber = RS_BEDROOM;
	if (random_range(2) && populate) make_house_npc(i,j);
	break;
      case 'H':
	Level->site[i][j].locchar = FLOOR;
	Level->site[i][j].roomnumber = RS_BEDROOM;
	if (random_range(2) && populate) make_mansion_npc(i,j);
	break;
      case 'D':
	Level->site[i][j].locchar = FLOOR;
	Level->site[i][j].roomnumber = RS_DININGROOM;
	break;
      case '.':
	Level->site[i][j].locchar = FLOOR;
	if (stops) {
	  lset(i,j,STOPS);
	  stops = 0;
	}
	break;
      case 'c':
	Level->site[i][j].locchar = FLOOR;
	Level->site[i][j].roomnumber = RS_CLOSET;
	break;
      case 'G':
	Level->site[i][j].locchar = FLOOR;
	Level->site[i][j].roomnumber = RS_BATHROOM;
	break;
      case 'B':
	Level->site[i][j].locchar = FLOOR;
	Level->site[i][j].roomnumber = RS_BEDROOM;
	break;
      case 'K':
	Level->site[i][j].locchar = FLOOR;
	Level->site[i][j].roomnumber = RS_KITCHEN;
	break;
      case 'S':
	Level->site[i][j].locchar = FLOOR;
	Level->site[i][j].showchar = WALL;
	lset(i,j,SECRET);
	Level->site[i][j].roomnumber = RS_SECRETPASSAGE;
	break;
      case '3':
	Level->site[i][j].locchar = SAFE;
	Level->site[i][j].showchar = WALL;
	lset(i,j,SECRET);
	Level->site[i][j].p_locf = L_SAFE;
	break;
      case '^':
	Level->site[i][j].locchar = FLOOR;
	Level->site[i][j].p_locf = TRAP_BASE+random_range(NUMTRAPS);
	break;
      case 'P':
	Level->site[i][j].locchar = PORTCULLIS;
	Level->site[i][j].p_locf = L_PORTCULLIS;
	break;
      case 'R':
	Level->site[i][j].locchar = FLOOR;
	Level->site[i][j].p_locf = L_RAISE_PORTCULLIS;
	break;
      case 'p':
	Level->site[i][j].locchar = FLOOR;
	Level->site[i][j].p_locf = L_PORTCULLIS;
	break;
      case 'T':
	Level->site[i][j].locchar = FLOOR;
	Level->site[i][j].p_locf = L_PORTCULLIS_TRAP;
	break;
      case 'X':
	Level->site[i][j].locchar = FLOOR;
	Level->site[i][j].p_locf = L_HOUSE_EXIT;
	stops = 1;
	break;
      case '#':
	Level->site[i][j].locchar = WALL;
	switch (kind) {
	  case E_HOVEL: Level->site[i][j].aux = 10; break;
	  case E_HOUSE: Level->site[i][j].aux = 50; break;
	  case E_MANSION: Level->site[i][j].aux = 150; break;
	}
	break;
      case '|':
	Level->site[i][j].locchar = OPEN_DOOR;
	Level->site[i][j].roomnumber = RS_CORRIDOR;
	lset(i,j,STOPS);
	break;
      case '+':
	Level->site[i][j].locchar = CLOSED_DOOR;
	Level->site[i][j].roomnumber = RS_CORRIDOR;
	Level->site[i][j].aux = LOCKED;
	lset(i,j,STOPS);
	break;
      case 'd':
	Level->site[i][j].locchar = FLOOR;
	Level->site[i][j].roomnumber = RS_CORRIDOR;
	if (populate)
	  make_site_monster(i,j,DOBERMAN);
	break;
      case 'a':
	Level->site[i][j].locchar = FLOOR;
	Level->site[i][j].roomnumber = RS_CORRIDOR;
	Level->site[i][j].p_locf = L_TRAP_SIREN;
	break;
      case 'A':
	Level->site[i][j].locchar = FLOOR;
	Level->site[i][j].roomnumber = RS_CORRIDOR;
	if (populate)
	  make_site_monster(i,j,AUTO_MINOR); /* automaton */
	break;
      }
      Level->site[i][j].showchar = ' ';
    }
  }
  map_close(home);
  initrand(E_RESTORE, 0);
}
Exemple #15
0
int rnd(int min, int max) {
	if (!rand_is_ready) initrand();
	return (int) (rand() * ((float) (max-min+1) / (float) RAND_MAX)) + min;
}