コード例 #1
0
ファイル: Desk.cpp プロジェクト: BackupTheBerlios/bblean
void ShowExplorer(void)
{
    struct hwnd_list *p;
    dolist (p, basebarlist)
        ShowWindow(p->hwnd, SW_SHOW);
    freeall(&basebarlist);
}
コード例 #2
0
ファイル: boot.c プロジェクト: yazshel/netbsd-kernel
static void
chain(void (*entry)(int (*)(void *), void *, u_int), char *args, void *ssym,
    void *esym)
{
	extern char end[];
	u_int l, magic = 0x19730224;

	freeall();

	/*
	 * Stash pointer to start and end of symbol table after the argument
	 * strings.
	 */
	l = strlen(args) + 1;
	l = (l + 3) & ~3;			/* align */
	DPRINTF("magic @ %p\n", args + l);
	memcpy(args + l, &magic, sizeof(magic));
	l += sizeof(magic);
	DPRINTF("ssym @ %p\n", args + l);
	memcpy(args + l, &ssym, sizeof(ssym));
	l += sizeof(ssym); 
	DPRINTF("esym @ %p\n", args + l);
	memcpy(args + l, &esym, sizeof(esym));
	l += sizeof(esym);
	DPRINTF("args + l -> %p\n", args + l);

	DPRINTF("Calling OF_chain(%p, %tx, %p, %p, %u)\n",
	    (void *)RELOC, end - (char *)RELOC, entry, args, l);
	OF_chain((void *)RELOC, end - (char *)RELOC, entry, args, l);
	panic("chain");
}
コード例 #3
0
ファイル: tree.cpp プロジェクト: alepharchives/Sablotron
AttSet::~AttSet()
{
    freeall(FALSE);
    //don't free this list items, these are copies of 
    //pointers stored with xsl:attribute-set element
    //usedSets.freeall(FALSE); 
    usedSets.deppendall(); 
}
コード例 #4
0
ファイル: tree.cpp プロジェクト: alepharchives/Sablotron
TmpList::~TmpList()
{
#ifdef _TH_DEBUG
  puts("TmpList destructor");
#endif
  //  dump();
  freeall(FALSE);
}
コード例 #5
0
//===========================================================================
void PluginManager_Exit()
{
    reverse_list(&bbplugins);
    struct plugins *q;
    dolist(q, bbplugins) q->enabled = false;
    load_all_plugins();
    freeall(&bbplugins);
}
コード例 #6
0
ファイル: uerror.c プロジェクト: abgoyal/pts-mini-gpl
/* Makes the current buffer the error buffer, possibly reparsing errors (if
 * it was a scratch buffer). Does not show the message count.
 */
int uthiserrbuf(BW *bw)
{
	if (errbuf != bw->b) {
		errbuf = bw->b;
		freeall();
	}
	reparserr();
	return 0;
}
コード例 #7
0
void freeall(struct listNode* temp)
{
    if(temp!=0)
    {
        freeall(temp->next);
    }
    free(temp);
    return;
}
コード例 #8
0
int main(void)
{
    initializeList();
    while(1)
    {
        printf("1. Insert new item. 2. Delete item. 3. Search item. \n");
        printf("4. Insert Last. 5. Delete Last. 6. Print forward. \n");
        printf("7. Print backward. 8. exit.\n");

        int ch;
        scanf("%d",&ch);
        if(ch==1)
        {
            int item;
            scanf("%d", &item);
            insertFirst(item);
        }
        else if(ch==2)
        {
            int item = deleteLast();
            if(item!=NULL_VALUE) printf("Deleted: %d\n", item);
        }
        else if(ch==3)
        {
            int item;
            scanf("%d", &item);
            struct listNode * res = searchItem(item);
            if(res!=0) printf("Found.\n");
            else printf("Not found.\n");
        }
        else if(ch==4)
        {
            int item;
            scanf("%d",&item);
            insertLast(item);
        }
        else if(ch==5)
        {
            deleteLast();
        }
        else if(ch==6)
        {
            printListForward();
        }
        else if(ch==7)
        {
            printListBackward();
        }
        else if(ch==8)
        {
            freeall(list);
            break;
        }
    }

}
コード例 #9
0
ファイル: polynomial.c プロジェクト: gs0622/test
int main(void)
{
    struct node *head = NULL;
    add(3, 2, &head);
    add(5, 1, &head);
    add(9, 0, &head);
    printall(head);
    freeall(head);
    return 0;
}
コード例 #10
0
ファイル: build_exit.c プロジェクト: noxsnono/42sh
void		build_exit(t_data *d)
{
	int	i;

	i = 0;
	if (ft_strlen(d->toexec) >= 5)
	{
		i = ft_atoi(&d->toexec[4]);
		i = i % 256;
	}
	freeall(d);
	_exit(i);
}
コード例 #11
0
ファイル: puredb_write.c プロジェクト: jedisct1/pure-ftpd
int puredbw_close(PureDBW * const dbw)
{
    if (writekeys(dbw) != 0) {
        return -1;
    }
    freestructs(dbw);
    if (mergefiles(dbw) != 0) {
        return -1;
    }
    freeall(dbw);

    return 0;
}
コード例 #12
0
void test_insert()
{
    Nameval *treep;
    treep = NULL;

    treep = insert(treep, newitem("dsjung", 29));
    treep = insert(treep, newitem("wwlee", 30));
    treep = insert(treep, newitem("arkim", 24));
    treep = insert(treep, newitem("shjo", 31));
    treep = insert(treep, newitem("dhkim", 33));

    applyinorder(treep, printnv, "%s: %d\n");
    freeall(treep);
}
コード例 #13
0
ファイル: prooftest.c プロジェクト: aaandrewww/authcontrol
void testall(){
  test_principal_eq();
  freeall();
  test_principal_cp();
  freeall();
  test_principal_subst();
  freeall();
  test_formula_eq();
  freeall();
  test_formula_cp();
  freeall();
  test_formula_subst();
  freeall();
  test_proof_eq();
  freeall();
  test_proof_check();
  freeall();
  member_context();
  freeall();
  free_context();
}
void mymain()
{
	int i;
	struct net net;
	personinit(&net);
	lineinit(&net);
	overlap(&net);
	statistics(&net);
	for (i = 0; i < STEP; i++)
	{
		spread(&net);
		recover(&net);
		statistics(&net);
		if (i % 10 == 0) printf("STEP %d...\n", i);
	}
	freeall(&net);
}
コード例 #15
0
int
main(int argc, char** argv)
{
  NDB_INIT("ndb_blob_tool");
  int ret;
  ndb_opt_set_usage_funcs(short_usage_sub, usage);
  ret = handle_options(&argc, &argv, my_long_options, ndb_std_get_one_option);
  if (ret != 0 || checkopts(argc, argv) != 0)
    return NDBT_ProgramExit(NDBT_WRONGARGS);

  setOutputLevel(opt_verbose ? 2 : 0);

  ret = doall();
  freeall();
  if (ret == -1)
    return NDBT_ProgramExit(NDBT_FAILED);
  return NDBT_ProgramExit(NDBT_OK);
}
int main(int argc, const char* argv[])
{
	FILE* fid = fopen("C://Users//LENOVO//Desktop//procedure.txt", "w");
	FILE* fp = fopen("C://Users//LENOVO//Desktop//result.txt", "w");
	int i;
	struct net net;
	if (fid == NULL || fp==NULL)
	{
		printf("Cannot open file!\n");
		return;
	}
	srand((unsigned)time(NULL));
	personinit(&net);
	lineinit(&net);
	overlap(&net);
	print(&net, fid);
	statistics(&net);
	prints(&net, fp);
	for (i = 0; i < STEP; i++)
	{
		spread(&net);
		recover(&net);
		print(&net, fid);
		statistics(&net);
		prints(&net, fp);
		if (i % 10 == 0) printf("STEP %d...\n", i);
	}
	fclose(fid);
	fclose(fp);
	printf("Done!\n");
	printf("Maximum percentage of I for disease 1 is: %g\n", max1);
	printf("Maximum percentage of I for disease 2 is: %g\n", max2);
	printf("Steady percentage of S for disease 1 is: %g\n", net.layer[0]->S);
	printf("Steady percentage of I for disease 1 is: %g\n", net.layer[0]->I);
	printf("Steady percentage of R for disease 1 is: %g\n", net.layer[0]->R);
	printf("Steady percentage of S for disease 2 is: %g\n", net.layer[1]->S);
	printf("Steady percentage of I for disease 2 is: %g\n", net.layer[1]->I);
	printf("Steady percentage of R for disease 2 is: %g\n", net.layer[1]->R);
	freeall(&net);
	system("pause");
	return 0;
}
コード例 #17
0
ファイル: cli-svr.c プロジェクト: leomurta/labgc-2012.2
void client(int argc, char **argv, char *abs_exe_path, char *path_invocation) {
    TBase * base = read_file();
    char arg[PATH_MAX] = "";

    if (argc > 1) {
        int i;
        for (i = 1; i < argc; i++) {
            strcat(arg, argv[i]);
            strcat(arg, " ");
        }
    }
    if (!base)
        return;
    int n = sprintf(abs_exe_path, "java -cp \"%s\" -Dbr.uff.ic.labgc.invocation=\"%s\" -Dbr.uff.ic.labgc.repository=\"%s\" -Djava.rmi.server.codebase=file:\"%s\" -Djava.rmi.server.hostname=%s -Djava.security.policy=\"%s\" br.uff.ic.labgc.AppCLI %s", base->jar_path, path_invocation, base->repository_path, base->rmi_path, base->rmi_host, base->policity_path, arg);
#ifdef __WIN32__
    abs_exe_path = slash(abs_exe_path);
#endif
    freeall(base);
    free(base);
}
コード例 #18
0
ファイル: comprima.c プロジェクト: gugacavalieri/dcc-ufmg-tps
int main(int argc, char** argv) {
    //SE OS ARGUMENTOS SÃO NULL'S , RETORNA
    if(argv[1] == NULL || argv[2] == NULL){
    printf("Falta argumentos para a funçao. Retornando.");
    return;
    }

    FILE *fp; //ponteiros de arquivo de escrita
    fp = fopen(argv[1] , "r"); // abre o arquivo para a primeira leitura
    if(fp == NULL) return;

    TipoLista l;
    FazListaVazia(&l);
    primeiraleitura(fp , &l);
    ordenaauxiliar(&l);
    crialista(&l);
    huffman(&l);
    fclose(fp); //fecha o arquivo
    fp = fopen(argv[1] , "r"); // abre o arquivo para a segunda leitura
    segundaleitura(fp , &l , argv[2]);
    fclose(fp); //fecha o arquivo novamente
    freeall(&l); //da free nas estruturas usadas
}
コード例 #19
0
void test_treesort()
{
    Nameval *treep;
    int i = 0;
    int p = 0;
    char *names[10] = {NULL};
    
    treep = NULL;
    treep = insert(treep, newitem("dsjung", 29));
    treep = insert(treep, newitem("wwlee", 30));
    treep = insert(treep, newitem("arkim", 24));
    treep = insert(treep, newitem("shjo", 31));
    treep = insert(treep, newitem("dhkim", 33));
    
    treesort(treep, &p, names);
    
    for (i = 0; i < 5; ++i) {
        if (NULL == names[i])
            break;
        printf("%s\n", names[i]);
    }
    
    freeall(treep);
}
コード例 #20
0
void delete_root(struct rootinfo *r)
{
    freeall(&r->paths);
}
コード例 #21
0
ファイル: Pidl.cpp プロジェクト: Jmos/bbclean-xzero450
//================================================
void delete_pidl_list (struct pidl_node **ppList)
{
	struct pidl_node *p;
	dolist (p, *ppList) m_free(p->v);
	freeall(ppList);
}
コード例 #22
0
ファイル: qspline.c プロジェクト: planetlabs/pyqspline
qspline(int n, int ns, double ds, int maxit, double tol, double* wi, double* wf, double* x, double* yflat,
  double* t, double* qflat, double* omegaflat, double* alphaflat)
/*
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

purpose

Subroutine qspline produces a quaternion spline interpolation of sparse data.
The method is based on a third-order polynomial expansion of the
rotation angle vector.

calling sequence

variable     i/o     description
--------     ---     -----------

n             i      number of input points (n >= 4).

ns            i      number of output points (ns >= 2).

ds            i      interval between output points (ds > 0.0).

maxit         i      maximum number of iterations.

tol           i      convergence tolerance (rad/sec) for iteration termination.

wi            i      initial angular rate vector.

wf            i      final angular rate vector.

x             i      pointer to input vector of time values.

y             i      pointer to input vector of quaternion values.

t             o      pointer to output vector of time values.

q             o      pointer to output array of interpolated quaternion values.

omega         o      pointer to output array of interpolated
                     angular rate values (rad/sec).

alpha         o      pointer to output array of interpolated
                     angular acceleration values (rad/sec^2).

return value

 ns >= 2 -> normal return, no error
 -1      -> insufficient input/output data (n < 4 or ns < 2)
 -2      -> independent variable is not monotonic increasing
 -3      -> memory allocation failure

external references

freeall
getang
rates
slew3_init
slew3

programming

J. J. McEnnan, April, 2003.

COPYRIGHT (C) 2003 by James McEnnan

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*/
{
  int i, j;
  double dx, xi, *h, *a, *b, *c, *dtheta, **e, **w, **wprev;
  double dum1[3], dum2[3], getang();

  double **y = (double **) malloc(n*sizeof(double*));
  for (i=0;i<n;i++) {
    y[i] = (double *) malloc(4*sizeof(double));
    for (j=0;j<4;j++) {
      y[i][j] = yflat[4*i+j];
    }
  }
  
  double **q = (double **) malloc(ns*sizeof(double*));
  double **omega = (double **) malloc(ns*sizeof(double*));
  double **alpha = (double **) malloc(ns*sizeof(double*));
  for (i=0;i<ns;i++){
    q[i] = (double *) malloc(4*sizeof(double));
    omega[i] = (double *) malloc(3*sizeof(double));
    alpha[i] = (double *) malloc(3*sizeof(double));
  }

  /* error checking. */

  if(n < 4)
  {
    fprintf(stderr,"qspline: insufficient input data.\n");

    return -1;
  }

  if(ds > 0.0)
  {
    dx = ds;

    ns = (int) ((x[n - 1] - x[0])/ds) + 1;
  }
  else
    dx = (x[n - 1] - x[0])/(ns - 1);

  if(ns < 2)
  {
    fprintf(stderr,"qspline: too few output points.\n");

    return -1;
  }

  i = n*sizeof(double);

  if((w = (double **) malloc((unsigned) i)) == DZERO)
  {
    fprintf(stderr,"qspline: memory allocation failure.\n");

    return -3;
  }

  if((wprev = (double **) malloc((unsigned) i)) == DZERO)
  {
    fprintf(stderr,"qspline: memory allocation failure.\n");

    free(w);

    return -3;
  }

  i = (n - 1)*sizeof(double);

  if((a = (double *) malloc((unsigned) i)) == ZERO)
  {
    fprintf(stderr,"qspline: memory allocation failure.\n");

    free(w);
    free(wprev);

    return -3;
  }

  if((b = (double *) malloc((unsigned) i)) == ZERO)
  {
    fprintf(stderr,"qspline: memory allocation failure.\n");

    free(w);
    free(wprev);
    free(a);

    return -3;
  }

  if((c = (double *) malloc((unsigned) i)) == ZERO)
  {
    fprintf(stderr,"qspline: memory allocation failure.\n");

    free(w);
    free(wprev);
    free(a);
    free(b);

    return -3;
  }

  if((h = (double *) malloc((unsigned) i)) == ZERO)
  {
    fprintf(stderr,"qspline: memory allocation failure.\n");

    free(w);
    free(wprev);
    free(c);
    free(b);
    free(a);

    return -3;
  }

  if((dtheta = (double *) malloc((unsigned) i)) == ZERO)
  {
    fprintf(stderr,"qspline: memory allocation failure.\n");

    free(w);
    free(wprev);
    free(c);
    free(b);
    free(a);
    free(dtheta);

    return -3;
  }

  if((e = (double **) malloc((unsigned) i)) == DZERO)
  {
    fprintf(stderr,"qspline: memory allocation failure.\n");

    free(w);
    free(wprev);
    free(e);
    free(dtheta);
    free(c);
    free(b);
    free(a);

    return -3;
  }

  for(i = 0;i < n;i++)
    w[i] = ZERO;

  for(i = 0;i < n;i++)
    wprev[i] = ZERO;

  for(i = 0;i < n - 1;i++)
    e[i] = ZERO;

  j = 3*sizeof(double);

  for(i = 0;i < n;i++)
    if((w[i] = (double *) malloc((unsigned) j)) == ZERO)
    {
      fprintf(stderr,"qspline: memory allocation failure.\n");

      freeall(n,h,a,b,c,dtheta,e,w,wprev);

      return -3;
    }

  for(i = 0;i < n;i++)
    if((wprev[i] = (double *) malloc((unsigned) j)) == ZERO)
    {
      fprintf(stderr,"qspline: memory allocation failure.\n");

      freeall(n,h,a,b,c,dtheta,e,w,wprev);

      return -3;
    }

  for(i = 0;i < n - 1;i++)
    if((e[i] = (double *) malloc((unsigned) j)) == ZERO)
    {
      fprintf(stderr,"qspline: memory allocation failure.\n");

      freeall(n,h,a,b,c,dtheta,e,w,wprev);

      return -3;
    }

  for(i = 0;i < n;i++)
    for(j = 0;j < 3;j++)
      w[i][j] = 0.0;

  for(i = 0;i < n - 1;i++)
  {
    h[i] = x[i + 1] - x[i];

    if(h[i] <= 0.0)
    {
      fprintf(stderr,"qspline: x is not monotonic.\n");

      freeall(n,h,a,b,c,dtheta,e,w,wprev);

      return -2;
    }
  }

  /* compute spline coefficients. */

  for(i = 0;i < n - 1;i++)
    dtheta[i] = getang(y[i],y[i + 1],e[i]);

  rates(n,maxit,tol,wi,wf,h,a,b,c,dtheta,e,w,wprev);

  /* interpolate and output results. */

  i = 0;
  xi = x[0];

  slew3_init(h[0],dtheta[0],e[0],w[0],dum1,w[1],dum2);

  for(j = 0;j < ns;j++)
  {
    while(xi >= x[i + 1] && i < n - 2)
    {
      i++;

      slew3_init(h[i],dtheta[i],e[i],w[i],dum1,w[i + 1],dum2);
    }

    t[j] = xi;

    slew3(xi - x[i],h[i],y[i],q[j],omega[j],alpha[j],dum1);

    xi += dx;
  }

  freeall(n,h,a,b,c,dtheta,e,w,wprev);

  for (i=0;i<ns;i++) {
    for (j=0;j<3;j++) {
      qflat[4*i+j] = q[i][j];
      omegaflat[3*i+j] = omega[i][j];
      alphaflat[3*i+j] = alpha[i][j];
    }
    qflat[4*i+3] = q[i][3];
    free(q[i]);
    free(omega[i]);
    free(alpha[i]);
  }
  free(q);
  free(omega);
  free(alpha);
  for (i=0;i<n;i++) {
    free(y[i]);
  }
  free(y);
  
  return ns;
}
コード例 #23
0
ファイル: cpari.c プロジェクト: AndreasBriese/cogtool
void fini_for_clisp (int leaving)
{
  /*free_graph();*/
  freeall();
  killallfiles(leaving);
}
コード例 #24
0
ファイル: main.c プロジェクト: neeph/pga_paralelo
int main(int argc,char *argv[])
{
   	//Inicia MPI
   	inicializa_mpi(argc,argv);
   	
  	// Obtiene rutas de trabajo y crea archivos generales
  	if(inicializa_archivos(argc, argv, rank) == -1) exit(-1); 
  	   
   	#ifdef _PRINT_MIGRACION_
   		printf("#Bienvenido a MAPAPOC (MÁquina PAralela para Problemas de Optimización Combinatoria) en Rank %d... [OK]\n", rank);
    #endif
      
   	if(rank != 0) {
            //Inicializa semilla aleatoria
            inicializa_semilla();

            //Espera que nodo0 entregue dato runmax (cantidad de archivos a procesar)
            for(;;){
                MPI_Iprobe(nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &flag1, &status);
                if(flag1 == true){
                    if (status.MPI_TAG == MSJ_RUNMAX){
                        MPI_Recv(&runmax, 1, MPI_INT, nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
                        flag1 = 0;
                        #ifdef _PRINT_MIGRACION_
                            printf("Rank = %d Recibió desde Rank = 0 Mensaje RUNMAX = %d (cantidad máxima de instancias a resolver)...\n", rank, runmax);
                        #endif
                        break;
                    }//End else if
                }//End if
            }//End for

            for(run=1; run<=runmax; run++) {
                #ifdef _PRINT_MIGRACION_
                        printf("Rank = %d Antes de generar semilla aleatoria...\n", rank);
                #endif
                //Nueva semilla aleatoria
                for(rank_seed = 1; rank_seed <= rank; rank_seed++) {
                    int s = 0;
/*
                    s = atoi(argv[7]);
*/
                    if(s==0) {
                        do {
                            randomseed = nueva_semilla();
                        } while (randomseed == 0);
                    } else {
                        randomseed = (float)((s%10000)/10000.0);
                    }
                }//End for
                #ifdef _PRINT_MIGRACION_
                    printf("Rank = %d Después de generar semilla aleatoria...\n", rank);
                #endif

                //Espera que nodo0 entregue información relevante para nodox
                for(;;) {
                    MPI_Iprobe(nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &flag1, &status);
                    if(flag1 == true){
                        if (status.MPI_TAG == MSJ_LINEA_IN){
                            MPI_Recv(linea_in, 100, MPI_CHAR, nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
                            flag1 = 0;
                            //Asigna variables globales desde linea_in recibida desde Rank 0
                            //sscanf(linea_in,"%d %s %d %s %d %f %f %f %d %s %f", &tipo_problema, nomarch, &popsize, answer, &maxgen, &pcross, &pmutation, &pind_env_rec, &tasa_migracion, answer_mod_mig, &randomseed);
                            sscanf(linea_in,"%d %s %d %s %d %f %f %f %f %d %s %f", &tipo_problema, nomarch, &popsize, answer, &maxgen, &pcross, &pmutation, &pind_env, &pind_rec, &tasa_migracion, answer_mod_mig, &randomseed);                 		
                            randomseed = randomseed + (rank * 0.001);
                            //printf("#Rank = %d estableción semilla : %f\n", rank, randomseed);
                            #ifdef _PRINT_MIGRACION_
                                printf("Rank = %d Recibió desde Rank = 0 Mensaje LINEA_IN (PARAMETROS GLOBALES)...\n", rank);
                            #endif
                        } else if (status.MPI_TAG == MSJ_CANT_CHAR_A_REC) {
                            //cantidad_char_a_recibir es la variable que indica cuantos enteros recibirá nodox desde Rank 0
                            MPI_Recv(&cantidad_char_a_recibir, 1, MPI_INT, nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
                            flag1 = 0;
                            #ifdef _PRINT_MIGRACION_
                            printf("Rank = %d Recibió desde Rank = 0 Mensaje MSJ_CANT_CHAR_A_REC...\n", rank);
                            #endif
                            break;
                        } else if (status.MPI_TAG == MSJ_ERROR_ARCHIVO_INSTANCIA) {
                            MPI_Recv(0, 0, MPI_INT, nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
                            flag1 = 0;
                            cantidad_char_a_recibir = -1; //setea a -1 para indicar que hubo error al leer archivo instancia
                            #ifdef _PRINT_MIGRACION_
                            printf("Rank = %d Recibió desde Rank = 0 Mensaje MSJ_ERROR_ARCHIVO_INSTANCIA...\n", rank);
                            #endif
                            break;
                        }//End else if
                    }//End if
                }//End for

                //Setea variable printstrings
                if(strncmp(answer,"n",1) == 0) printstrings = 0;
                else printstrings = 1;

                //Setea variables dependiendo de la cantidad de workers 
                popsize = popsize / workers;
                if(popsize%2) popsize++;
                //n_ind_a_enviar = (int) popsize * pind_env_rec;  //% de la subpoblación se envía
                //n_ind_a_recibir = (int) popsize * pind_env_rec; //% de la subpoblación se recibe
                n_ind_a_enviar = (int) popsize * pind_env;  //% de la subpoblación se envía
                n_ind_a_recibir = (int) popsize * pind_rec; //% de la subpoblación se recibe
                //tasa_migracion = maxgen / workers; //tasa de migración depende de la cantidad de generaciones
                #ifdef _PRINT_MIGRACION_
                    printf("Rank = %d tiene popsize %d, n_ind_a_enviar %d, n_ind_a_recibir %d, tasa_migracion %d...\n", rank, popsize, n_ind_a_enviar, n_ind_a_recibir, tasa_migracion);
                #endif

                // nro. que identifica que migración está ocurriendo
                n_migracion = 0;

                //Inicializa contador de segundos de comunicación 
                time_comm = 0.0;

                //Setea variable modelo_migracion
                if(strncmp(answer_mod_mig,"A",1) == 0) modelo_migracion = 0; // Migración Asíncrona
                else modelo_migracion = 1; //Migración Síncrona

                #ifdef _PRINT_MIGRACION_
                    printf("Rank %d debería recibir %d caracteres representando la instancia a resolver...\n", rank, cantidad_char_a_recibir);
                #endif

                if(cantidad_char_a_recibir > 0) {
                    //Lee enteros con información del archivo instancia  
                    if(lee_char_y_genera_achivo_instancia_tmp(tipo_problema, cantidad_char_a_recibir)) {
                        #ifdef _PRINT_MIGRACION_
                                printf("Espere, MAPAPOC en Rank %d está procesando archivo %s...\n", rank, nomarch);
                        #endif

                        //Actualiza Resultados Estadísticos Evolutivos para cada problema particular
                        fprintf(evofp, "\n\nCorrida : %d, PROBLEMA : %s\n", run, nomarch);
                        fprintf(evofp, "Migracion Generacion Minimo Maximo Media DesvEstandar TiempoTranscurrido GenMejor\n");
                        // Inicia la cuenta de Segundos
                        time_start = MPI_Wtime();

                        // Rutina de inicialización de variables globales
                        initialize();

                        // Ubica espacio malloc para las estructuras de datos globales
                        initmalloc();

                        // Define tipos de Individuos a Enviar y Recibir
                        Build_type_pop(envpop, &message_type_send, n_ind_a_enviar);
                        Build_type_pop(recpop, &message_type_receive, n_ind_a_recibir);

                        // Initializa la población de individuos y determina datos estadísticos
                        // y mejor individuo de la población
                        initpop(tipo_problema);
                        statistics(oldpop);

                        //Avisa a nodo0 que esté listo para comenzar evolución...
                        time_send = MPI_Wtime();
                        MPI_Isend(0, 0, MPI_INT, nodo0, MSJ_LISTO_PARA_COMENZAR, MPI_COMM_WORLD, &request);
                        for(;;){
                            MPI_Test(&request, &flag2, &status);
                            if(flag2 == true){
                            time_send = MPI_Wtime() - time_send;
                            time_comm += time_send;
                            #ifdef _PRINT_MIGRACION_
                                    printf("Envió desde Rank = %d a Rank = 0 Mensaje Listo para comenzar...\n", rank);
                            #endif
                            break;
                            }//End If
                        }//End for

                            //Espera que nodo0 dé la partida para comenzar evolución...
                        for(;;){
                            MPI_Iprobe(nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &flag1, &status);
                            if(flag1 == true) {
                                if (status.MPI_TAG == MSJ_COMIENCE){
                                    MPI_Recv(0, 0, MPI_INT, nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
                                    flag1 = 0;
                                    #ifdef _PRINT_MIGRACION_
                                            printf("Rank = %d Recibió desde Rank = 0 Mensaje de COMINECE, comienza evolución...\n", rank);
                                    #endif
                                    break;
                                }//End if
                            }//End if
                        }//End for

                        //Setea contador de generaciones para Migrar en Modelo de Migración Asíncrona
                        if (modelo_migracion == 0) cuenta_gen_para_migracion=1;

                        for(gen=0; gen<maxgen; gen++) {
                            if(printstrings == 1) fprintf(outfp,"\nGENERATION %d->%d\n",gen,maxgen);
                            // Crea una nueva generación
                            generation(tipo_problema);
/*
                            printf("generacion: %d de %d => %f\n",gen, maxgen, bestfit.fitness);
*/

                            // Efectúa estadísticas sobre nueva población y obtiene mejor individuo
                            statistics(newpop);

                            if (modelo_migracion == 0) 
                            //Establece comunicación Asincrona con Coordinador
                            comunicacion_asincrona_con_coordinador();         
                            else
                            //Establece comunicación sincrona con Coordinador
                            comunicacion_sincrona_con_coordinador();    
/*
                            printf("rank %i gen %i best fitness: %f\n", rank, gen, bestfit.fitness);
*/
/*
                            if(bestfit.fitness < 107.0) {
                                printf("rank %i gen %i best fitness: %f done!\n", rank, gen, bestfit.fitness);
                                gen = maxgen;
                            }
*/
/*
                            printf("%i.%i=>%f\n", rank, gen, bestfit.fitness);
*/
                            // Avanza de Generación
                            temppop = oldpop;
                            oldpop = newpop;
                            newpop = temppop;
                        }//End for

                            // Libera memoria temporal
                        freeall();

                            //Libera memoria tipos creados por MPI
                        MPI_Type_free(&message_type_send);
                        MPI_Type_free(&message_type_receive);

                    } else
                        printf("!!! ADVERTENCIA ¡¡¡ Rank %d no procesó archivo de instancia ya que hubo problemas al leer enteros, generar o leer tmp...\n", rank);
                } else 
                    printf("!!! ADVERTENCIA ¡¡¡ Rank %d no procesó archivo de instancia ya que Rank 0 tuvo problemas al leerlo...\n", rank);

                // Libera variables del problema  
                app_free(tipo_problema);

                //Mensaje de término de procesamiento de archivo actual se envía a Rank = 0
                MPI_Isend(&time_comm, 1, MPI_DOUBLE, nodo0, MSJ_TERMINO, MPI_COMM_WORLD, &request);
                for(;;){
                    MPI_Test(&request, &flag2, &status);
                    if(flag2 == true){
                        #ifdef _PRINT_MIGRACION_
                            printf("Envió desde Rank = %d a Rank = 0 Mensaje de Término, archivo %s...\n", rank, nomarch);
                        #endif
                        break;
                    }//End If
                }//End for

                    //Espera que nodo0 dé el OK para poder finalizar el procesamiento del archivo actual
                for(;;){
                    MPI_Iprobe(nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &flag1, &status);
                    if(flag1 == true){
                        if(status.MPI_TAG == MSJ_TERMINO_CONFIRMADO){
                            MPI_Recv(0, 0, MPI_INT, nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
                            flag1 = 0;
                            #ifdef _PRINT_MIGRACION_
                                printf("Rank = %d Recibió desde Rank = 0 Mensaje de TERMINO_CONFIRMADO, pasa siguiente archivo o termina...\n", rank);
                            #endif
                            break;
                        }//End if
                    }//End if
                }//End for
                #ifdef _PRINT_MIGRACION_
                        printf("#Corrida %d, Archivo %s procesado por Rank %d...   [OK]\n", run, nomarch, rank);
                #endif
            }//End for

            if(runmax == 0){
                //Que runmax = 0 significa que la consistencia del archivo arrojó un error 
                //=> rank debe mandar mensaje al Coordinador que va ha terminar el proceso...
                //Mensaje de término de procesamiento de archivo actual se envía a Rank = 0
                MPI_Isend(&time_comm, 1, MPI_DOUBLE, nodo0, MSJ_TERMINO, MPI_COMM_WORLD, &request);
                for(;;){
                    MPI_Test(&request, &flag2, &status);
                    if(flag2 == true){
                        #ifdef _PRINT_MIGRACION_
                                printf("Envió desde Rank = %d a Rank = 0 Mensaje de Término, archivo %s...\n", rank, nomarch);
                        #endif
                        break;
                    }//End If
                }//End for
                printf("Proceso en Rank %d detenido ya que Rank 0 informa error en archivo de entrada...   [OK]\n", rank);
            }//End if
        } else {
      	//Rank = 0 => Coordinador
/*
   		printf("#Bienvenido a Máquina Paralela para Problemas de Optimización Combinatoria, espere por favor...\n");
*/
      	
      	// Revisa consistencia del archivo de entrada in.txt
      	runmax = consistenciaarchivo(workers);
      	
      	//Envía runmax a cada Rank
      	envia_a_cada_rank(MSJ_RUNMAX);
   
      	for(run=1;run<=runmax;run++) {
         	//Lee archivo en infp con parametros (todos ya chequeados)
         	//OJO => Cada AG tendrá popsize/workers individuos => Población Total = popsize          	
			//fscanf(infp,"%d %s %d %s %d %f %f %f %d %s %f", &tipo_problema, nomarch, &popsize, answer, &maxgen, &pcross, &pmutation, &pind_env_rec, &tasa_migracion, answer_mod_mig, &randomseed);
            fscanf(infp,"%d %s %d %s %d %f %f %f %f %d %s %f", &tipo_problema, nomarch, &popsize, answer, &maxgen, &pcross, &pmutation, &pind_env, &pind_rec, &tasa_migracion, answer_mod_mig, &randomseed);
            int i=0;
            randomseed = (float)((atoi(argv[7])%100)/100.0);
            
/*
            printf("argv[7]: %i\n", atoi(argv[7]));
            printf("randomseed: %f\n", randomseed);
*/
            for(i=0; i<argc; i++) {
//                printf("argv[%i]: %s\n", i, argv[i]);
                if(strcmp(argv[i], "-pr")==0) tipo_problema = atoi(argv[++i]);
                if(strcmp(argv[i], "-po")==0) popsize = atoi(argv[++i]);
                if(strcmp(argv[i], "-g")==0) maxgen = atoi(argv[++i]);
                if(strcmp(argv[i], "-m")==0) pmutation = atof(argv[++i]);
                if(strcmp(argv[i], "-c")==0) pcross = atof(argv[++i]);
                if(strcmp(argv[i], "-pe")==0) pind_env = atof(argv[++i]);
                if(strcmp(argv[i], "-pa")==0) pind_rec = atof(argv[++i]);
                if(strcmp(argv[i], "-tm")==0) tasa_migracion = atoi(argv[++i]);
                if(strcmp(argv[i], "-am")==0) sprintf(answer_mod_mig, "%s", argv[++i]);
                if(strcmp(argv[i], "-f")==0) sprintf(nomarch, "%s", argv[++i]);
                if(strcmp(argv[i], "-a")==0) sprintf(answer, "%s", argv[++i]);
            }
//            exit(0);
         	
			//Inicializa contador de segundos de comunicación 
         	time_comm = 0.0;
         
         	//Llena con información linea_in para ser enviada a cada Rank
         	//sprintf(linea_in,"%d %s %d %s %d %f %f %f %d %s %f\n", tipo_problema, nomarch, popsize, answer, maxgen, pcross, pmutation, pind_env_rec, tasa_migracion, answer_mod_mig, randomseed);
			sprintf(linea_in,"%d %s %d %s %d %f %f %f %f %d %s %f", tipo_problema, nomarch, popsize, answer, maxgen, pcross, pmutation, pind_env, pind_rec, tasa_migracion, answer_mod_mig, randomseed);
/*
                        printf("%d %s %d %s %d %f %f %f %f %d %s %f\n", tipo_problema, nomarch, popsize, answer, maxgen, pcross, pmutation, pind_env, pind_rec, tasa_migracion, answer_mod_mig, randomseed);
*/

       		#ifdef _PRINT_MIGRACION_
       			printf("Espere, MAPAPOC en Rank %d está enviando archivo %s a todos los rank...\n", rank, nomarch);
       		#endif

        	//Envía linea_in a cada Rank
      		envia_a_cada_rank(MSJ_LINEA_IN);
      	
         	//Setea variable printstrings
         	if(strncmp(answer,"n",1) == 0) printstrings = 0;
         	else printstrings = 1;
      
         	//Setea variables dependiendo de la cantidad de workers 
         	popsize = popsize / workers;
/*
                printf("popsize: %i\n", popsize);
*/
         	if(popsize%2) popsize++;
         	//n_ind_a_enviar = (int) popsize * pind_env_rec;  //% de la subpoblación se envía
         	//n_ind_a_recibir = (int) popsize * pind_env_rec; //% de la subpoblación se recibe
                n_ind_a_enviar = (int) popsize * pind_env;  //% de la subpoblación se envía
         	n_ind_a_recibir = (int) popsize * pind_rec; //% de la subpoblación se recibe
         	//tasa_migracion = maxgen / workers; //tasa de migración debende de la cantidad de generaciones
               
         	//Setea variable modelo_migracion
         	if(strncmp(answer_mod_mig,"A",1) == 0) modelo_migracion = 0; //Migración Asíncrona
         	else modelo_migracion = 1; //Migración Síncrona
         
         	if(app_leearchivo(tipo_problema, nomarch, rank)) {     
            	if(almacena_archivo_instancia(nomarch)) {
	            	//Determina cantidad_char_a_recibir por cada rank que coordinador enviará. Todos estos char determinan los datos del problema a resolver
	            	cantidad_char_a_recibir = cantidad_char_que_determinan_instancia_del_problema;
	            	
	            	//Envía a cada Rank cantidad de char a recibir del problema
	            	envia_a_cada_rank(MSJ_CANT_CHAR_A_REC); 
	            
	            	//Envía a cada Rank un grupo de char que determinan la estructura de una instancia del problema
	            	envia_a_cada_rank(MSJ_CHAR_ARCHIVO_INSTANCIA);
	            	
	        		// Rutina de inicialización de variables globales
	           		// nro. individuos a enviar desde coord. a nodo AG
	           		coord_ind_a_env  = n_ind_a_recibir;  
	           		// nro. individuos a recibir desde cada nodo AG a coord
	           		coord_ind_a_rec = n_ind_a_enviar; 
	           		// nro. individuos total recibidos => Población Global del Coordinador
	           		coord_ind_global = workers * n_ind_a_enviar; 
	           		// nro. que identifica qué migración está ocurriendo
	           		n_migracion = 1;  
	           		#ifdef _PRINT_MIGRACION_
	           			printf("Espere, MAPAPOC en Rank %d está procesando archivo %s...\n", rank, nomarch);
	              		printf("Rank = %d tiene popsize %d, coord_ind_a_env %d, coord_ind_a_rec %d, coord_ind_global % d, tasa_migracion %d...\n", rank, popsize, coord_ind_a_env, coord_ind_a_rec, coord_ind_global, tasa_migracion);
	           		#endif
	     
				   	//Actualiza Resultados Estadísticos Evolutivos para cada problema particular
				   	fprintf(evofp, "\n\nCorrida : %d, PROBLEMA : %s\n", run, nomarch);
				   	fprintf(evofp, "Migracion Generacion Minimo Maximo Media DesvEstandar TiempoTranscurrido\n");
				   	// Inicia la cuenta de Segundos
				   	time_start = MPI_Wtime();
	           
	           		//Rutina de inicialización de variables globales
	           		initialize();
	           
	           		//Dimensiona poblaciones de individuos que recibe y envía...
	           		initmallocMaster(coord_ind_a_rec, coord_ind_a_env, coord_ind_global);
	     
	           		//Define tipos de Individuos a Enviar y Recibir
	           		Build_type_pop(envpop, &message_type_send, coord_ind_a_env);
	           		Build_type_pop(recpop, &message_type_receive, coord_ind_a_rec);
	  
	           		if (modelo_migracion == 0) 
	              		//Establece comunicación Asincrona con cada rank (AG)
		              		comunicacion_asincrona_con_cada_rank();         
	           		else
	              		//Establece comunicación sincrona con cada rank (AG)
	              		comunicacion_sincrona_con_cada_rank();         
	              
                                // Calcula cantidad de segundos que demoró en cada Algoritmo Genético
                                time_end = MPI_Wtime() - time_start;
                                time_consumation.elapsed_time = time_end;
                                time_consumation.comm_time = time_comm;
                                time_consumation.cpu_time = time_end - time_comm;

                                //Graba datos en archivo de resultados del algoritmo
                                genera_resultados_algoritmo(run, tipo_problema, nomarch, &time_consumation);

                                //Graba datos en archivo de resultados del problema
                                app_genera_resultados_problema(run, tipo_problema, nomarch);

                                //IMPRIME SALIDA PARA PROGRAMA PARAMILS
/*
                                printf("RunsExecuted = 1\n");
                                printf("CPUTime_Mean = %f\n", time_consumation.elapsed_time);
                                printf("BestSolution_Mean = %f\n", bestfit.fitness);
*/
/*
                                printf("Result for ParamILS: SAT, %f, %i, %f, %s\n", -1.0, -1, bestfit.fitness, argv[7]);
*/
                                printf("Resultado: SAT, %s, %f, %f, %f, %f\n", nomarch, time_consumation.elapsed_time, time_consumation.cpu_time, bestfit.fitness, randomseed);

                                //Genera la Salida hacia archivo de Resultados LAYOUT
                                app_objfuncfinal(tipo_problema, &(bestfit));
				  	
	           		//Libera memoria del Coordinador
	           		freeallMaster(coord_ind_a_rec, coord_ind_a_env, coord_ind_global);
	           
	           		//Libera memoria tipos creados por MPI
	           		MPI_Type_free(&message_type_send);
	           		MPI_Type_free(&message_type_receive);
	         	}//End if
	         	else {
	            	printf("!!! ERROR ¡¡¡ Rank 0, en datos del archivo de piezas <%s> => Archivo no procesado...\n", nomarch);
	            	//Envía a cada Rank que ARCHIVO_INSTANCIA está con algún error
	            	envia_a_cada_rank(MSJ_ERROR_ARCHIVO_INSTANCIA); 
	         	}//End else
         	}//End if
         	else {
            	printf("!!! ERROR ¡¡¡ Rank 0, en datos del archivo de piezas <%s> => Archivo no procesado...\n", nomarch);
            	//Envía a cada Rank que ARCHIVO_INSTANCIA está con algún error
            	envia_a_cada_rank(MSJ_ERROR_ARCHIVO_INSTANCIA); 
         	}//End else
	      	// Libera variables del problema  
	      	app_free(tipo_problema);

                #ifdef _PRINT_MIGRACION_
         		printf("#Corrida %d, Archivo %s procesado por Coordinador...   [OK]\n", run, nomarch);
         	#else
//         		printf("#Corrida %d, Archivo %s procesado...   [OK]\n", run, nomarch);
         	#endif
      	}//End for
      	if(runmax == 0){
         	//Que runmax = 0 significa que la consistencia del archivo arrojó un error 
         	printf("Archivo %s NO procesado por Rank %d debido a error...   [OK]\n", nomarch, rank);
      	}//End if
   	}//End else    

	//Cierra archivos
	cierra_archivos();
	
   	//Rutina para MPI
   	MPI_Finalize();
 
   	#ifdef _PRINT_MIGRACION_
   		printf("Terminó rank = %d...\n", rank);
    #endif
   
	exit(0);
}//End main
コード例 #25
0
ファイル: boot.c プロジェクト: ryo/netbsd-src
/*
 * Prepare boot information and jump directly to the kernel.
 */
static void
jump_to_kernel(u_long *marks, char *kernel, char *args, void *ofw,
	int boothowto)
{
	int l, machine_tag;
	long newargs[4];
	void *ssym, *esym;
	vaddr_t bootinfo;
	struct btinfo_symtab bi_sym;
	struct btinfo_kernend bi_kend;
	struct btinfo_boothowto bi_howto;
	char *cp;
	char bootline[PROM_MAX_PATH * 2];

	/* Compose kernel boot line. */
	strncpy(bootline, kernel, sizeof(bootline));
	cp = bootline + strlen(bootline);
	if (*args) {
		*cp++ = ' ';
		strncpy(bootline, args, sizeof(bootline) - (cp - bootline));
	}
	*cp = 0; args = bootline;

	/* Record symbol information in the bootinfo. */
	bootinfo = bi_init(marks[MARK_END]);
	bi_sym.nsym = marks[MARK_NSYM];
	bi_sym.ssym = marks[MARK_SYM];
	bi_sym.esym = marks[MARK_END];
	bi_add(&bi_sym, BTINFO_SYMTAB, sizeof(bi_sym));
	bi_kend.addr= bootinfo + BOOTINFO_SIZE;
	bi_add(&bi_kend, BTINFO_KERNEND, sizeof(bi_kend));
	bi_howto.boothowto = boothowto;
	bi_add(&bi_howto, BTINFO_BOOTHOWTO, sizeof(bi_howto));
	if (bootinfo_pass_bootdev) {
		struct {
			struct btinfo_common common;
			char name[256];
		} info;
		
		strcpy(info.name, bootdev);
		bi_add(&info, BTINFO_BOOTDEV, strlen(bootdev)
			+sizeof(struct btinfo_bootdev));
	}

	sparc64_finalize_tlb(marks[MARK_DATA]);
	sparc64_bi_add();

	ssym  = (void*)(long)marks[MARK_SYM];
	esym  = (void*)(long)marks[MARK_END];

	DPRINTF(("jump_to_kernel(): ssym = %p, esym = %p\n", ssym, esym));

	/* Adjust ksyms pointers, if needed. */
	if (COMPAT_BOOT(marks) || compatmode) {
		ksyms_copyout(&ssym, &esym);
	}

	freeall();
	/*
	 * When we come in args consists of a pointer to the boot
	 * string.  We need to fix it so it takes into account
	 * other params such as romp.
	 */

	/*
	 * Stash pointer to end of symbol table after the argument
	 * strings.
	 */
	l = strlen(args) + 1;
	memcpy(args + l, &esym, sizeof(esym));
	l += sizeof(esym);

	/*
	 * Tell the kernel we're an OpenFirmware system.
	 */
	machine_tag = SPARC_MACHINE_OPENFIRMWARE;
	memcpy(args + l, &machine_tag, sizeof(machine_tag));
	l += sizeof(machine_tag);

	/* 
	 * Since we don't need the boot string (we can get it from /chosen)
	 * we won't pass it in.  Just pass in esym and magic #
	 */
	newargs[0] = SPARC_MACHINE_OPENFIRMWARE;
	newargs[1] = (long)esym;
	newargs[2] = (long)ssym;
	newargs[3] = (long)(void*)bootinfo;
	args = (char *)newargs;
	l = sizeof(newargs);

	/* if -D is set then pause in the PROM. */
	if (debug > 1) callrom();

	/*
	 * Jump directly to the kernel. Solaris kernel and Sun PROM
	 * flash updates expect ROMP vector in %o0, so we do. Format
	 * of other parameters and their order reflect OF_chain()
	 * symantics since this is what older NetBSD kernels rely on.
	 * (see sparc64/include/bootinfo.h for specification).
	 */
	DPRINTF(("jump_to_kernel(%lx, %lx, %lx, %lx, %lx) @ %p\n", (long)ofw,
				(long)args, (long)l, (long)ofw, (long)ofw,
				(void*)marks[MARK_ENTRY]));
	(*(entry_t)marks[MARK_ENTRY])((long)ofw, (long)args, (long)l, (long)ofw,
				      (long)ofw);
	printf("Returned from kernel entry point!\n");
}
コード例 #26
0
ファイル: nano.c プロジェクト: jigsaw121/nanofic
void end(scene* now, int retcode) {
    freeall(now);
	savestate();
	pause(now, &s_skip);
    exit(retcode);
}
コード例 #27
0
ファイル: puredb_write.c プロジェクト: jedisct1/pure-ftpd
void puredbw_free(PureDBW * const dbw)
{
    freestructs(dbw);
    freeall(dbw);
}
コード例 #28
0
ファイル: tree.cpp プロジェクト: alepharchives/Sablotron
VarDirectory::~VarDirectory()
{
    freeall(FALSE);
}
コード例 #29
0
ファイル: ReactToSig.c プロジェクト: FRuffy/sys_prak
/**
 * Signal "SIGUSR1": Der Vater ruft den Thinker auf.
 * Signal "SIGINT" : CTRL + C wurde gedrueckt - Vater und Kind beenden sich
 *
 * @param SHM, signal (0 = Zug soll berechnet werden | 1 = CTRL + C wurde gedrueckt),
 * config_struct für free-Befehl, fd[] fuer Spielzug, shmID zum detatchen zur zerstoren des shm
 * @return 0 bei Sielzug in Pipe geschrieben, -1 bei Fehler
 */
int reactToSig(sharedmem* shm, int signal, config_struct *conf, int fd[], int shmID) {
	/* Zug soll berechnet werden */
	if (signal == 0) {
		/* Signal SIGUSR1 wurde empfangen */
		int err;
		(void) signal;
		shm->pf = shmat(shm->pfID, 0, 0);

		/* Sicherstellen, dass SIGUSR1 vom Kind kam */
		if (shm->pleaseThink == 1) {
			shm->pleaseThink = 0;
			if (think(shm) != 0) {
				return EXIT_FAILURE;
			}

			char* reply = calloc(15, sizeof(char));
			addchar(reply);
			if (shm->nextStone == -1) {
				sprintf(reply, "PLAY %s", shm->nextField);
			} else {
				sprintf(reply, "PLAY %s,%d", shm->nextField, shm->nextStone);
			}

			/* Spielzug in Pipe schreiben */
			err = write(fd[1], reply, 15);

			if (err < 0) {
				perror("\nFehler beim Schreiben in die Pipe\n");
				return EXIT_FAILURE;
			}

			/* Denken beendet */
			shm->thinking = 0;
		}

	} else if (signal == 1) {
		/* CTRL + C wurde gedrueckt */
		fclose(logdatei);
		free(conf);
		freeall();
		if (shm->pidKid == getpid()) {
			/* Kind */
			close(fd[0]);
			close(shm->sock);
			shmdt(shm->pf);
			shmdt(shm);
		} else {
			/* Vater */
			close(fd[1]);
			if (shm->pfID != 0) {
				shmdt(shm->pf);
				if (shmctl(shm->pfID, IPC_RMID, NULL ) == -1) {
					perror("\nParent: Fehler bei Zerstoerung von pf \n");
				}
			}
			shmdt(shm);
			if (shmctl(shmID, IPC_RMID, NULL ) == -1) {
				perror("\nParent: Fehler bei Zerstoerung von shm \n");
			}
		}

		exit(EXIT_FAILURE);
	}

	return EXIT_SUCCESS;
}
コード例 #30
0
ファイル: tree.cpp プロジェクト: alepharchives/Sablotron
AttSetList::~AttSetList()
{
    freeall(FALSE);
}