Example #1
0
int main(int argc, char *argv[], char *envp[])
	{
	char	answer[128], filename[64];
	int	cache_page, line_offset, value;
	FILE	*logfp;
	int	i, j, k, ret;
	int	*tmparray;	/* for malloc'd static array */
	struct	rlimit rlims;
	struct	rusage	r_start, r_stop;

	cache_page = getpagesize();

			/* Ask for line_offset */
again:	fprintf(stdout, "\nEnter line_offset: ");
	fgets(answer, sizeof(answer) - 1, stdin);
	fflush(stdin);
	line_offset = atoi(answer);
	if ( (cache_page < line_offset) || (line_offset < 1) )
		{
		fprintf(stderr,
			"\nline_offset=%d out of range [1, %d]",
				line_offset, cache_page); 
		fflush(stderr);
		goto again;
		}

			/* Reduce MAX_RSS to be NICE to other users */
#if defined(__alpha)
	rlims.rlim_cur = NEW_MAX_RSS;		/* soft */
	rlims.rlim_max = NEW_MAX_RSS;		/* hard */
	if(setrlimit(RLIMIT_RSS, &rlims) < 0)
		{
		perror("setrlimit: ");
		exit(-1);
		} 
#endif
			/* Reduce our priority to be NICE to other users 
		PRIO_MAX is 20 on pegasus so we are doing nice(19) */
	if (nice(PRIO_MAX - 1) < 0)
		{
		perror("nice: ");
		exit(-1);
		}

			/* open log file */
	sprintf(filename, "cache_%4.4d.log", line_offset);
	logfp = fopen(filename, "w");	
	if (logfp == (FILE *)NULL)
		{
		fprintf(stderr, 
	  "\n\nmain: *** fopen(\"%s\",\"w\") failed ***\n\n", filename);
		fflush(stderr);
		return(-3);
		}

			/* get starting baseline resource usage */
	ret = get_resource_usage(RUSAGE_SELF, &r_start);
	if (ret != 0)
		{
		fprintf(stderr,
		"\n..get_resource_usage(RUSAGE_SELF,..) return %d ", ret);
		fflush(stderr);
		}
			/* initialize and start timers */
	init_timing();

			/* allocate tmparray[] in data segment */
	tmparray = (int *)malloc(NUM_ENTRIES * cache_page * sizeof(int));
	if (tmparray == (int *)NULL)
		{
		fprintf(stderr,
			"\nmalloc: fatal error:");
		fflush(stderr);
		exit(-4);
		}
	fprintf(stdout,
		"\nUsing line_offset=%d cache_page=%d..",
			line_offset, cache_page);
	fflush(stdout);
	fprintf(logfp,
		"\nUsing line_offset=%d cache_page=%d..",
			line_offset, cache_page);
	fflush(logfp);

	value = 0;
	for (k = 0 ; k < REPEAT ; k++)
	    {
	    i = 0;	/* only for fprintf() */
    	    j = 0;
	    if ((k % 32) == 0)
		{
		fprintf(stdout,
	"\n..setting entry, tmparry[], value [%9d,%9d,%9d]", i, j, value);
		fflush(stdout);
		}
	    for (i = 0 ; i < NUM_ENTRIES ; i++)
		{
		tmparray[j] = value;	/* tmparray[j] will be kept
				in the L2 cache until cache contention
				with newer data forces it to be written
				out to (slower) main memory */
		j = j + line_offset;
		value++; 

		if  ( ((i % 1024) == 0) && ((k % 32) == 0) )
			{
			putchar(0x08); putchar(0x08);
			putchar(0x08); putchar(0x08);
			putchar(0x08); putchar(0x08);
			putchar(0x08); putchar(0x08);
			putchar(0x08); putchar(0x08);
			putchar(0x08); putchar(0x08);
			putchar(0x08); putchar(0x08);
			putchar(0x08); putchar(0x08);
			putchar(0x08); putchar(0x08);
			putchar(0x08); putchar(0x08);
			putchar(0x08); putchar(0x08);
			putchar(0x08); putchar(0x08);
			putchar(0x08); putchar(0x08);
			putchar(0x08); putchar(0x08);
			putchar(0x08); putchar(0x08);
			fprintf(stdout, "%9d,%9d,%9d]", i, j, value);
			fflush(stdout);
			} 
		}  /* end of for (i = .. */
	    }  /* end of for (k = .. */

			/* get ending resource usage */
	ret = get_resource_usage(RUSAGE_SELF, &r_stop);
	if (ret != 0)
		{
		fprintf(stderr,
		"\n..get_resource_usage(RUSAGE_SELF,..) return %d ", ret);
		fflush(stderr);
		}

			/* read timers and then stop them */
	read_timing(&real_sec, &real_usec, &virt_sec, &virt_usec,
			&prof_sec, &prof_usec);
	pause_timing();

			/* print out resources used in rusage struct's 
		to both stdout and our logfile */
	fprintf(stdout, "\n..stopping timers ");
	fprintf_rusage(stdout, &r_start, &r_stop);

	fprintf(logfp, "\n..stopping timers ");
	fprintf_rusage(logfp, &r_start, &r_stop);

			/* printout the total times to both stdout and
		our logfile */
	printf_timing();
	fprintf(stdout, "\nNet Memory Bandwidth %8.3f Mbytes/sec: ",
  ((double)(value*sizeof(int))/((double)prof_sec + (double)prof_usec/1000000.0))
		/1000000.0 );
	fprintf(stdout, "\n\n");
	fflush(stdout);

	fprintf_timing(logfp,
	  real_sec, real_usec, virt_sec, virt_usec, prof_sec, prof_usec);
	fprintf(logfp, "\nNet Memory Bandwidth %8.3f Mbytes/sec: ",
  ((double)(value*sizeof(int))/((double)prof_sec + (double)prof_usec/1000000.0))
		/1000000.0 );
	fprintf(logfp, "\n\n");
	fflush(logfp);
	fclose(logfp);	/* close logfile */
	return(0);
	}  /* end of main */
Example #2
0
int ReadASPData(struct ASPHdr *hdr, struct SubHdr *subhdr, 
		 struct RunVars *RunMode, fitsfile *Fin, int nscan, 
		 int NPtsProf, double **ASquared, double **BSquared, 
		 double **ReAconjB, double **ImAconjB, long **SampleCount)
{

  int  i, j, status=0, datacolnum, refcolnum, anynull;
  int  NColumns;
  
  char Rawfile[100];

  FILE *s;


  fits_get_num_cols(Fin, &NColumns, &status);status=0;


  /* malloc array for each channel based on profile size */
  for(i=0;i<hdr->obs.NChan;i++){
    ASquared[i]    = (double *)malloc(NPtsProf*sizeof(double));
    DZero(&ASquared[i][0], NPtsProf);
    BSquared[i]    = (double *)malloc(NPtsProf*sizeof(double));
    DZero(&BSquared[i][0], NPtsProf);
    ReAconjB[i]    = (double *)malloc(NPtsProf*sizeof(double));
    DZero(&ReAconjB[i][0], NPtsProf);
    ImAconjB[i]    = (double *)malloc(NPtsProf*sizeof(double));
    DZero(&ImAconjB[i][0], NPtsProf);
    SampleCount[i] = (long   *)malloc(NPtsProf*sizeof(long));
    LZero(&SampleCount[i][0], NPtsProf);
  }


  /* get middle dump time  */
  if(!strcmp(hdr->gen.HdrVer,"Ver1.0")) 
    fits_read_key(Fin, TDOUBLE, "DUMPMIDSECS", &(subhdr->DumpMiddleSecs), 
		  NULL, &status); status = 0;
  

  /* move to ref table for newer version */
  if(!strcmp(hdr->gen.HdrVer,"Ver1.0.1")) {
    fits_read_key(Fin, TDOUBLE, "MIDSECS", &(subhdr->DumpMiddleSecs), 
		  NULL, &status); status = 0;
    refcolnum = 0;
    fits_read_col(Fin, TDOUBLE, ++refcolnum, 1, 1, (long)hdr->obs.NChan, NULL, 
		  subhdr->DumpRefPhase,  &anynull, &status); 
    fits_read_col(Fin, TDOUBLE, ++refcolnum, 1, 1, (long)hdr->obs.NChan, NULL, 
		  subhdr->DumpRefPeriod, &anynull, &status); 


   if(RunMode->Verbose){
      printf("Dump %d:  TIME OF DUMP = %lf\n",nscan,subhdr->DumpMiddleSecs); 
      printf("          CHANNEL (MHz)   REF. PHASE   REF. PERIOD (s)\n");
      printf("          -------------   ----------   ---------------\n");
      for(i=0;i<hdr->obs.NChan;i++) 
	printf("          %13.1lf%13.8lf%18.11lf\n", hdr->obs.ChanFreq[i],
	       subhdr->DumpRefPhase[i], subhdr->DumpRefPeriod[i]);       
      fflush(stdout);
    }

    /* Move to next HDU, i.e. data table for this dump */
    fits_movrel_hdu(Fin, 1, NULL, &status);
  }


  datacolnum = 0;

  for(i=0;i<hdr->obs.NChan;i++) {

    fits_read_col(Fin, TDOUBLE,  ++datacolnum, 1, 1, NPtsProf, NULL, 
		  &ASquared[i][0],    &anynull, &status); 
    fits_read_col(Fin, TDOUBLE,  ++datacolnum, 1, 1, NPtsProf, NULL, 
		  &BSquared[i][0],    &anynull, &status); 
    fits_read_col(Fin, TDOUBLE,  ++datacolnum, 1, 1, NPtsProf, NULL, 
		  &ReAconjB[i][0],    &anynull, &status); 
    fits_read_col(Fin, TDOUBLE,  ++datacolnum, 1, 1, NPtsProf, NULL, 
		  &ImAconjB[i][0],    &anynull, &status); 
    if(!RunMode->OldFits)
      fits_read_col(Fin, TLONG,  ++datacolnum, 1, 1, NPtsProf, NULL, 
		    &SampleCount[i][0], &anynull, &status); 

/* Normalize */
    
    if(!RunMode->OldFits){
      for(j=0;j<NPtsProf;j++){
        ASquared[i][j] /= (double)SampleCount[i][j];
        BSquared[i][j] /= (double)SampleCount[i][j];
        ReAconjB[i][j] /= (double)SampleCount[i][j];
        ImAconjB[i][j] /= (double)SampleCount[i][j];

      }
    }

  }


  for(i=0;i<hdr->obs.NChan;i++) {

   /* read in reference phase, period if old version */


    if(!strcmp(hdr->gen.HdrVer,"Ver1.0")){
      fits_read_key(Fin, TDOUBLE, "DUMPREFPER",   &(subhdr->DumpRefPeriod[i]),  
		    NULL, &status); status = 0;
      fits_read_key(Fin, TDOUBLE, "DUMPREFPHASE", &(subhdr->DumpRefPhase[i]),   
		    NULL, &status); status = 0; 
                                                                              
      if(RunMode->Verbose && i==0){
	printf("Dump %d:  TIME OF DUMP = %lf\n",nscan, subhdr->DumpMiddleSecs);
	printf("          REF. PHASE = %lf, REF. PERIOD = %lf s\n", 
	       subhdr->DumpRefPhase[i], subhdr->DumpRefPeriod[i]);fflush(stdout);
      }
    }


    /*
   sprintf(HeadLine[i],"# %.1f %.7f %.10f %ld %.3f %.3f %d %s %d %s %.10f",
	    (double)hdr->obs.IMJDStart, subhdr->DumpMiddleSecs, 
	    subhdr->DumpRefPeriod[i], (long)1,hdr->obs.ChanFreq[i], hdr->obs.DM, 
	    RunMode->NBinsOut, hdr->obs.ObsvtyCode, 1, hdr->target.PSRName, 
	    subhdr->DumpRefPhase[i]);

    if (RunMode->MakeRaw){
      sprintf(Rawfile,"%s.%4.4d.%4.4d.prof.raw.asc",RunMode->OutfileRoot,
	      (int)(hdr->obs.ChanFreq[i]),nscan);
      s = fopen(Rawfile, "w");
      if (s==NULL) {
	printf("ASPFitsReader: Can't open file %s\n",Rawfile);
	fflush(stdout);
	exit(1);
      }

      fprintf(s,"%s\n",HeadLine[i]);

      for (j=0; j<NPtsProf; j++) {
 	fprintf(s,"%d  %lf  %lf  %lf  %lf  %d\n",j, 
		ASquared[i][j], BSquared[i][j], ReAconjB[i][j], ImAconjB[i][j],
		SampleCount[i][j]); 
      }
      fclose(s);

    }
    */

  }

  return 1;

}
static GstFlowReturn
gst_festival_chain (GstPad * pad, GstBuffer * buf)
{
  GstFlowReturn ret = GST_FLOW_OK;
  GstFestival *festival;
  guint8 *p, *ep;
  gint f;
  FILE *fd;

  festival = GST_FESTIVAL (GST_PAD_PARENT (pad));

  GST_LOG_OBJECT (festival, "Got text buffer, %u bytes", GST_BUFFER_SIZE (buf));

  f = dup (festival->info->server_fd);
  if (f < 0)
    goto fail_open;
  fd = fdopen (f, "wb");
  if (fd == NULL) {
    close (f);
    goto fail_open;
  }

  /* Copy text over to server, escaping any quotes */
  fprintf (fd, "(Parameter.set 'Audio_Required_Rate 16000)\n");
  fflush (fd);
  GST_DEBUG_OBJECT (festival, "issued Parameter.set command");
  if (read_response (festival) == FALSE) {
    fclose (fd);
    goto fail_read;
  }

  fprintf (fd, "(tts_textall \"");
  p = GST_BUFFER_DATA (buf);
  ep = p + GST_BUFFER_SIZE (buf);
  for (; p < ep && (*p != '\0'); p++) {
    if ((*p == '"') || (*p == '\\')) {
      putc ('\\', fd);
    }

    putc (*p, fd);
  }
  fprintf (fd, "\" \"%s\")\n", festival->info->text_mode);
  fclose (fd);

  GST_DEBUG_OBJECT (festival, "issued tts_textall command");

  /* Read back info from server */
  if (read_response (festival) == FALSE)
    goto fail_read;

out:
  gst_buffer_unref (buf);
  return ret;

  /* ERRORS */
fail_open:
  {
    GST_ELEMENT_ERROR (festival, RESOURCE, OPEN_WRITE, (NULL), (NULL));
    ret = GST_FLOW_ERROR;
    goto out;
  }
fail_read:
  {
    GST_ELEMENT_ERROR (festival, RESOURCE, READ, (NULL), (NULL));
    ret = GST_FLOW_ERROR;
    goto out;
  }
}
Example #4
0
BOOL DbgPrint(__in LPCTSTR lpszFormatString, ...)
{
    BOOL    bResult = TRUE;

    va_list VAList;
    va_start(VAList, lpszFormatString);

    if (g_bSaveLogFile)
    {
#if defined(DBG_THREADSAFE)
        OS_CAutoLock lock(s_mtxEntry);
#endif
        if (!s_bLogPathInit)
        {
            SYSTEMTIME stime = {0};
            GetLocalTime(&stime);
#if defined(UNDER_CE)
            _stprintf(s_szLogFile, _T("%s\\log_%04d%02d%02d_%d.log"), g_bLogSavePath, stime.wYear, stime.wMonth, stime.wDay, GetTickCount());
#else
            _stprintf_s(s_szLogFile, MAX_PATH, _T("%s\\log_%04d%02d%02d_%d.log"), g_bLogSavePath, stime.wYear, stime.wMonth, stime.wDay, GetTickCount());
#endif
            s_bLogPathInit = true;
        }

        FILE* pFile = _tfopen(s_szLogFile, _T("a"));
        if (pFile != NULL)
        {
            fseek(pFile,SEEK_END,0);
            long cbSize = ftell(pFile);
            if (cbSize > MAX_LOG_FILE_SIZE)
            {
                fclose(pFile);
                {
                    SYSTEMTIME stime = {0};
                    GetLocalTime(&stime);
#if defined(UNDER_CE)
                    _stprintf(s_szLogFile, _T("%s\\log_%04d%02d%02d_%d.log"), g_bLogSavePath, stime.wYear, stime.wMonth, stime.wDay, GetTickCount());
#else
                    _stprintf_s(s_szLogFile, MAX_PATH, _T("%s\\log_%04d%02d%02d_%d.log"), g_bLogSavePath, stime.wYear, stime.wMonth, stime.wDay, GetTickCount());
#endif
                    s_bLogPathInit = true;
                }
                pFile = _tfopen(s_szLogFile, _T("a"));
                if (pFile == NULL)
                {
                    return FALSE;
                }
            }
            _vftprintf(pFile, lpszFormatString, VAList);
            fflush(pFile);
            fclose(pFile);
            pFile = NULL;
        }
    }
    else
    {
#if defined(UNDER_CE)
        _vtprintf(lpszFormatString, VAList);
#else
        TCHAR szBuf[MAX_PATH * 2] = {0};
        _vstprintf_s(szBuf, MAX_PATH, lpszFormatString, VAList);
        OutputDebugString(szBuf);
#endif
    }
    va_end(VAList);

    return bResult;
}
Example #5
0
/**
 * rank and size are the MPI rank and size, respectively.
 * from and to denote the global(!) range of lines that this process is responsible for.
 *
 * Example with 9 matrix lines and 4 processes:
 * - rank 0 is responsible for 1-2, rank 1 for 3-4, rank 2 for 5-6 and rank 3 for 7.
 *   Lines 0 and 8 are not included because they are not calculated.
 * - Each process stores two halo lines in its matrix (except for ranks 0 and 3 that only store one).
 * - For instance: Rank 2 has four lines 0-3 but only calculates 1-2 because 0 and 3 are halo lines for other processes. It is responsible for (global) lines 5-6.
 */
static
void
DisplayMatrixMPI (struct calculation_arguments* arguments, struct calculation_results* results, struct options* options, int rank, int size, int from, int to)
{
    int const elements = 8 * options->interlines + 9;

    int x, y;
    double** Matrix = arguments->Matrix[results->m];
    MPI_Status status;

    /* first line belongs to rank 0 */
    if (rank == 0)
        from--;

    /* last line belongs to rank size - 1 */
    if (rank + 1 == size)
        to++;

    if (rank == 0)
        printf("Matrix:\n");

    for (y = 0; y < 9; y++)
    {
        int line = y * (options->interlines + 1);

        if (rank == 0)
        {
            /* check whether this line belongs to rank 0 */
            if (line < from || line > to)
            {
                /* use the tag to receive the lines in the correct order
                 * the line is stored in Matrix[0], because we do not need it anymore */
                MPI_Recv(Matrix[0], elements, MPI_DOUBLE, MPI_ANY_SOURCE, 42 + y, MPI_COMM_WORLD, &status);
            }
        }
        else
        {
            if (line >= from && line <= to)
            {
                /* if the line belongs to this process, send it to rank 0
                 * (line - from + 1) is used to calculate the correct local address */
                MPI_Send(Matrix[line - from + 1], elements, MPI_DOUBLE, 0, 42 + y, MPI_COMM_WORLD);
            }
        }

        if (rank == 0)
        {
            for (x = 0; x < 9; x++)
            {
                int col = x * (options->interlines + 1);

                if (line >= from && line <= to)
                {
                    /* this line belongs to rank 0 */
                    printf("%7.4f", Matrix[line][col]);
                }
                else
                {
                    /* this line belongs to another rank and was received above */
                    printf("%7.4f", Matrix[0][col]);
                }
            }

            printf("\n");
        }
    }

    fflush(stdout);
}
int main(int argc, char **argv){

	extern char *optarg;
	int c;

	/* We default to 1 second updates and displaying in bytes*/
	int delay = 1;
	char units = 'b';

	sg_disk_io_stats *diskio_stats;
	int num_diskio_stats;

	/* Parse command line options */
	while ((c = getopt(argc, argv, "d:bkm")) != -1){
		switch (c){
			case 'd':
				delay =	atoi(optarg);
				break;
			case 'b':
				units = 'b';
				break;
			case 'k':
				units = 'k';	
				break;
			case 'm':
				units = 'm';
				break;
		}
	}

	/* Initialise statgrab */
	sg_init();

	/* Drop setuid/setgid privileges. */
	if (sg_drop_privileges() != 0) {
		perror("Error. Failed to drop privileges");
		return 1;
	}

	/* We are not interested in the amount of traffic ever transmitted, just differences. 
	 * Because of this, we do nothing for the very first call.
	 */

	diskio_stats = sg_get_disk_io_stats_diff(&num_diskio_stats);
	if (diskio_stats == NULL){
		perror("Error. Failed to get disk stats");
		return 1;
	}

	/* Clear the screen ready for display the disk stats */
	printf("\033[2J");

	/* Keep getting the disk stats */
	while ( (diskio_stats = sg_get_disk_io_stats_diff(&num_diskio_stats)) != NULL){
		int x;
		int line_number = 2;

		long long total_write=0;
		long long total_read=0;

		for(x = 0; x < num_diskio_stats; x++){	
			/* Print at location 2, linenumber the interface name */
			printf("\033[%d;2H%-25s : %-10s", line_number++, "Disk Name", diskio_stats->disk_name);
			/* Print out at the correct location the traffic in the requsted units passed at command time */
			switch(units){
				case 'b':
					printf("\033[%d;2H%-25s : %8lld b", line_number++, "Disk read", diskio_stats->read_bytes);
					printf("\033[%d;2H%-25s : %8lld b", line_number++, "Disk write", diskio_stats->write_bytes);
					break;
				case 'k':
					printf("\033[%d;2H%-25s : %5lld k", line_number++, "Disk read", (diskio_stats->read_bytes / 1024));
					printf("\033[%d;2H%-25s : %5lld", line_number++, "Disk write", (diskio_stats->write_bytes / 1024));
					break;
				case 'm':
					printf("\033[%d;2H%-25s : %5.2f m", line_number++, "Disk read", diskio_stats->read_bytes / (1024.00*1024.00));
					printf("\033[%d;2H%-25s : %5.2f m", line_number++, "Disk write", diskio_stats->write_bytes / (1024.00*1024.00));
			}
			printf("\033[%d;2H%-25s : %ld ", line_number++, "Disk systime", (long) diskio_stats->systime);

			/* Add a blank line between interfaces */	
			line_number++;

			/* Add up this interface to the total so we can display a "total" disk io" */
			total_write+=diskio_stats->write_bytes;
			total_read+=diskio_stats->read_bytes;

			/* Move the pointer onto the next interface. Since this returns a static buffer, we dont need
			 * to keep track of the orginal pointer to free later */
			diskio_stats++;
		}

		printf("\033[%d;2H%-25s : %-10s", line_number++, "Disk Name", "Total Disk IO");
		switch(units){
			case 'b':
				printf("\033[%d;2H%-25s : %8lld b", line_number++, "Disk Total read", total_read);
				printf("\033[%d;2H%-25s : %8lld b", line_number++, "Disk Total write", total_write);
				break;
			case 'k':
				printf("\033[%d;2H%-25s : %5lld k", line_number++, "Disk Total read", (total_read / 1024));
				printf("\033[%d;2H%-25s : %5lld k", line_number++, "Disk Total write", (total_write / 1024));
				break;
			case 'm':
				printf("\033[%d;2H%-25s : %5.2f m", line_number++, "Disk Total read", (total_read  / (1024.00*1024.00)));
				printf("\033[%d;2H%-25s : %5.2f m", line_number++, "Disk Total write", (total_write  / (1024.00*1024.00)));
				break;
		}

		fflush(stdout);

		sleep(delay);

	}

	return 0;

}
Example #7
0
File: vm.c Project: 0x73/wren
static void write(WrenVM* vm, const char* text)
{
  printf("%s", text);
  fflush(stdout);
}
Example #8
0
File: cdmf.c Project: LuaDist/cd
static void cdflush(cdCtxCanvas *ctxcanvas)
{
  fflush(ctxcanvas->file);
  fprintf(ctxcanvas->file, "%d\n", CDMF_FLUSH);
}
Example #9
0
void test_COM1(void)
{
	char pressKey, *dev = "/dev/ttyS0", *s=NULL, *st;
	char *lf = strcat(dirname(gppath(getpid())), "/ppp.log");
	int l, m, n=0;
	FILE *com, *gprs, *pl;
	pthread_t ti, to;
	pid_t gid = 0;

	va_list ap;

	while (1)
	{
		printf("Press 'o' try to open COM1\n");
		printf("Press 'c' try to close COM1\n");
		printf("Press 'e' exit COM1 test\n");

		pressKey=getchar();

		printf("\n");

		switch (pressKey)
		{
			case 'o':
				com = fopen_sp(dev, B115200, 8, 0, 1, TTYS_TEXT_MODE);
				if (com != NULL)
					printf("Open COM1 OK! Pointer of COM: %p(address: %p)\n", com, &com);
				else
				{
					printf("Open COM1 error!\n");
					break;					
				}

				ti=to=0;
				
				if (pthread_create(&ti, NULL, send_to_com, (void *)com) != 0)
				{
					printf("Create send thread fail!\n");
					break;
				}
				if (pthread_create(&to, NULL, read_from_com, (void *)com) != 0)
				{
					printf("Create read thread fail!\n");
					break;
				}
				pthread_join(ti, NULL);

				char *arg[]={
					"pppd",
					"/dev/ttyS0",			//Serial device is ttyS0(COM1)
					"115200",				//Buad in 115200
					"modem",				//Waitting for CD signal
					"nocrtscts",			//Disabled hardware RTS & CTS
					"nodetach",				//Disable detach from terminal.
					"usepeerdns",			//Ask the peers for up to 2 DNS
					"noipdefault",			//Local ip supply by peers
					"defaultroute",			//Using the peers as gateway
					"user", "\"cmnet\"",
					"0.0.0.0:0.0.0.0",		//local ip:remote ip
					"ipcp-accept-local",	//Accept peer supply local IP
					"noccp",				//Disable CCP(Compression Control Protocol)
					"persist",				//hold connection
					"lcp-echo-interval", "5",	//Send LCP echo frame every 30 seconds
					"lcp-echo-failure", "5",	//Retry times when LCP echo fail
					"chap-interval", "5",		//rechallenge the peer every 5 seconds
					NULL};

				gprs = ppopen(&gid, "pppd", arg, "rn");
				if (NULL == gprs)
				{
					printf("Call pppd fail!\n");
					break;
				}
				pl = fopen(lf, "a");
				if (NULL == pl)
				{
					printf("Open log file fail!\n");
					break;
				}

				l = 0;
				time_t t;
				for (;;)
				{
					while (getline(&s, &n, gprs)<=0);
				
					t = time(NULL);
					st = sctime(&t);

					fprintf(pl, "%s>%s", st, s);
					fflush(pl);
					printf("%s>%s", st, s);

					if ((strstr(s, "terminated") != NULL) || (strstr(s, "failed") != NULL))
					{
						l = -1;
						printf("PPPD fail!\n");
						fprintf(pl, "\n%s>---PPPD fail!---\n", st);
						break;
					}

									switch (l)
					{
						case 0:
							if (strstr(s, PPPD_LOCAL_IP_STR) != NULL)
							{
								l++;
								printf("%d>>Got local IP\n", l);
							}
							break;
						case 1:
							if (strstr(s, PPPD_REMOTE_IP_STR) != NULL)
							{
								l++;
								printf("%d>>Got remote IP\n", l);
							}
							break;
						case 2:
							if (strstr(s, PPPD_PRIMARY_DNS_STR) != NULL)
							{
								l++;
								printf("%d>>Got primary dns\n", l);
							}
							break;
						case 3:
							if (strstr(s, PPPD_SECONDARY_DNS_STR) != NULL)
							{
								l++;
								printf("%d>>Got secondary dns\n", l);
							}
							break;
					}
					if (l == 4) 
					{
						printf("Got all str!\n");
						// break;
					}
				}

				if (l == -1)
				{
					printf("Close pipe file!\n");
					fclose(gprs);
					printf("Kill pppd! PID: %d\n", gid);
					kill(gid, SIGKILL);
					waitpid(gid, NULL, 0);
				}
				break;
			case 'c':
				fclose_sp(com);
		}
		if (pressKey=='e')
		{
			if (NULL != gprs) fclose(gprs);
			if (0 != gid)
			{
				kill(gid, SIGKILL);
				waitpid(gid, NULL, 0);
			}
			break;
		}
	}
}
Example #10
0
void main ()
{
    func (2, 1., 2., 3.);
    pass ("func [OKI002]");
    fflush (stdout);
}
Example #11
0
int main(int argc, char **argv)
{
        char **my_argv, *name = argv[0], *grp;
        int status, c, i;
        int gid_is_set = 0, uid_is_set = 0, num_supp = -1;
        uid_t user_id = 0;
        gid_t grp_id = 0, supp_groups[NGROUPS_MAX] = { 0 };
        int euid_is_set = 0, egid_is_set = 0;
        uid_t euid = 0;
        gid_t egid = 0;

        if (argc == 1) {
                fprintf(stderr, "No parameter count\n");
                Usage_and_abort(name);
        }

        // get UID and GID
        while ((c = getopt(argc, argv, "+u:g:v:j:hG::")) != -1) {
                switch (c) {
                case 'u':
                        if (!isdigit(optarg[0])) {
                                struct passwd *pw = getpwnam(optarg);
                                if (pw == NULL) {
                                        fprintf(stderr, "parameter '%s' bad\n",
                                                optarg);
                                        Usage_and_abort(name);
                                }
                                user_id = pw->pw_uid;
                        } else {
                                user_id = (uid_t)atoi(optarg);
                        }
                        uid_is_set = 1;
                        if (!gid_is_set)
                                grp_id = user_id;
                        break;

                case 'g':
                        if (!isdigit(optarg[0])) {
                                struct group *gr = getgrnam(optarg);
                                if (gr == NULL) {
                                        fprintf(stderr, "getgrname %s failed\n",
                                                optarg);
                                        Usage_and_abort(name);
                                }
                                grp_id = gr->gr_gid;
                        } else {
                                grp_id = (gid_t)atoi(optarg);
                        }
                        gid_is_set = 1;
                        break;

                case 'v':
                        if (!isdigit(optarg[0])) {
                                struct passwd *pw = getpwnam(optarg);
                                if (pw == NULL) {
                                        fprintf(stderr, "parameter '%s' bad\n",
                                                optarg);
                                        Usage_and_abort(name);
                                }
                                euid = pw->pw_uid;
                        } else {
                                euid = (uid_t)atoi(optarg);
                        }
                        euid_is_set = 1;
                        break;

                case 'j':
                        if (!isdigit(optarg[0])) {
                                struct group *gr = getgrnam(optarg);
                                if (gr == NULL) {
                                        fprintf(stderr, "getgrname %s failed\n",
                                                optarg);
                                        Usage_and_abort(name);
                                }
                                egid = gr->gr_gid;
                        } else {
                                egid = (gid_t)atoi(optarg);
                        }
                        egid_is_set = 1;
                        break;

                case 'G':
                        num_supp = 0;
                        if (optarg == NULL || !isdigit(optarg[0]))
                                break;
                        while ((grp = strsep(&optarg, ",")) != NULL) {
                                printf("adding supp group %d\n", atoi(grp));
                                supp_groups[num_supp++] = atoi(grp);
                                if (num_supp >= NGROUPS_MAX)
                                        break;
                        }
                        break;

                default:
                case 'h':
                        Usage_and_abort(name);
                        break;
                }
        }

        if (!uid_is_set) {
                fprintf(stderr, "Must specify uid to run.\n");
                Usage_and_abort(name);
        }

        if (optind == argc) {
                fprintf(stderr, "Must specify command to run.\n");
                Usage_and_abort(name);
        }

        // assemble the command
        my_argv = (char**)malloc(sizeof(char*)*(argc+1-optind));
        if (my_argv == NULL) {
                fprintf(stderr, "Error in allocating memory. (%s)\n",
                        strerror(errno));
                exit(-1);
        }

        for (i = optind; i < argc; i++) {
                my_argv[i-optind] = argv[i];
                //printf("%s\n",my_argv[i-optind]);
        }
        my_argv[i-optind] = NULL;

#if DEBUG
        system("whoami");
#endif

        // set GID
        if (!egid_is_set)
                egid = grp_id;
        status = setregid(grp_id, egid);
        if (status == -1) {
                 fprintf(stderr, "Cannot change gid to %d/%d, errno=%d (%s)\n",
                         grp_id, egid, errno, strerror(errno) );
                 exit(-1);
        }

        if (num_supp >= 0) {
                status = setgroups(num_supp, supp_groups);
                if (status == -1) {
                        perror("setting supplementary groups");
                        exit(-1);
                }
        }

        // set UID
        if (!euid_is_set)
                euid = user_id;
        status = setreuid(user_id, euid);
        if(status == -1) {
                  fprintf(stderr,"Cannot change uid to %d/%d, errno=%d (%s)\n",
                           user_id, euid, errno, strerror(errno) );
                  exit(-1);
        }

        fprintf(stderr, "running as uid/gid/euid/egid %d/%d/%d/%d, groups:",
                user_id, grp_id, euid, egid);
        for (i = 0; i < num_supp; i++)
                fprintf(stderr, " %d", supp_groups[i]);
        fprintf(stderr, "\n");

        for (i = 0; i < argc - optind; i++)
                 fprintf(stderr, " [%s]", my_argv[i]);

        fprintf(stderr, "\n");
        fflush(stderr);

        // The command to be run
        execvp(my_argv[0], my_argv);
        fprintf(stderr, "execvp fails running %s (%d): %s\n", my_argv[0],
                errno, strerror(errno));
        exit(-1);
}
Example #12
0
static __inline__ gint
nmp_debug_create_log_file(const gchar *file_folder, const gchar *name)
{
    gint err;
    time_t time_now;
    struct tm tm_now;
    gchar file_name[MAX_FILE_NAME];
    gchar log_file_path[PATH_MAX];
    gchar old_file_path[PATH_MAX];

    if (!file_folder || !name)
        return -E_INVAL;

    if ((err = nmp_debug_create_path(file_folder,
        PATH_FOLDER_PERM, log_file_path)))
        return err;

	memset(file_name, 0, sizeof(file_name));
    strncpy(file_name, name, MAX_FILE_NAME - 1);
    strcpy(old_file_path, log_file_path);

    if (strlen(log_file_path) + strlen(file_name)
        + 2 > PATH_MAX)
        return -ENAMETOOLONG;

    time_now = time(NULL);

    strcat(log_file_path, "/");
    strcat(log_file_path, file_name);

    log_file = fopen(log_file_path, "r");
    if (log_file)
    {
        fclose(log_file);
        log_file = NULL;

        if (!localtime_r(&time_now, &tm_now))
            return -errno;

        sprintf(file_name + strlen(file_name), 
            "."HM_LOG_TIME_FORMAT, 
            tm_now.tm_year + 1900, 
            tm_now.tm_mon + 1, 
            tm_now.tm_mday, 
            tm_now.tm_hour, 
            tm_now.tm_min, 
            tm_now.tm_sec
        );

        if (strlen(old_file_path) + strlen(file_name)
            + 2 > PATH_MAX)
            return -ENAMETOOLONG;

        strcat(old_file_path, "/");
        strcat(old_file_path, file_name);
        rename(log_file_path, old_file_path);
    }

    log_file = fopen(log_file_path, "w");
    if (log_file)
    {
        fprintf(log_file, HM_LOG_TITLE, ctime(&time_now));
        fflush(log_file);
    }

    return log_file ? 0 : -errno;
}
int main(int argc, char ** argv){
  float Z, M, M_MIN;
  char cmnd[1000];
  FILE *LOG;
  time_t start_time, curr_time;

  time(&start_time);

  // make appropriate directories
  system("mkdir ../Log_files");
  system("mkdir ../Boxes");

  // open log file
  system("rm ../Log_files/*");
  LOG = fopen("../Log_files/drive_zscroll_noTs_log_file", "w");
  if (!LOG){
    fprintf(stderr, "drive_zscroll_log_file.c: Unable to open log file\n Aborting...\n");
    return -1;
  }

  Z = ZSTART;
  while (Z > (ZEND-0.0001)){
    fprintf(stderr, "*************************************\n");

    M_MIN = get_M_min_ion(Z);

    // if USE_HALO_FIELD is turned on in ANAL_PARAMS.H, run the halo finder
    if (USE_HALO_FIELD){
      //  the following only depend on redshift, not ionization field
      // find halos
      sprintf(cmnd, "./find_halos %f", Z);
      time(&curr_time);
      fprintf(stderr, "Now calling: %s, %g min have ellapsed\n", cmnd, difftime(start_time, curr_time)/60.0);
      fprintf(LOG, "Now calling: %s, %g min have ellapsed\n", cmnd, difftime(start_time, curr_time)/60.0);
      fflush(NULL);
      system(cmnd);


      // shift halos accordig to their linear velocities
      sprintf(cmnd, "./update_halo_pos %f", Z);
      time(&curr_time);
      fprintf(stderr, "Now calling: %s, %g min have ellapsed\n", cmnd, difftime(start_time, curr_time)/60.0);
      fprintf(LOG, "Now calling: %s, %g min have ellapsed\n", cmnd, difftime(start_time, curr_time)/60.0);
      fflush(NULL);
      system(cmnd);
    }

    // shift density field and update velocity field
    sprintf(cmnd, "./perturb_field %f", Z);
    time(&curr_time);
    fprintf(stderr, "Now calling: %s, %g min have ellapsed\n", cmnd, difftime(start_time, curr_time)/60.0);
    fprintf(LOG, "Now calling: %s, %g min have ellapsed\n", cmnd, difftime(start_time, curr_time)/60.0);
    fflush(NULL);
    system(cmnd);
    // end of solely redshift dependent things, now do ionization stuff


    fprintf(stderr, "*************************************\n");
    fflush(NULL);
    Z += ZSTEP;
  }

  fclose(LOG);
  return 0;
}
Example #14
0
/* Get output stream pointer (open and write header if new and noopen==0) */
STREAMOUT *
getostream(const char *ospec, const char *mname, int bn, int noopen)
{
	static STREAMOUT	stdos;
	char			info[1024];
	int			ofl;
	char			oname[1024];
	LUENT			*lep;
	STREAMOUT		*sop;
	char			*cp;
	
	if (ospec == NULL) {			/* use stdout? */
		if (!noopen & !using_stdout) {
			if (outfmt != 'a')
				SET_FILE_BINARY(stdout);
			if (header) {
				cp = info;
				if (yres > 0) {
					sprintf(cp, "NROWS=%d\n", yres *
							(xres + !xres) );
					while (*cp) ++cp;
				}
				if ((xres <= 0) | (stdos.reclen > 1))
					sprintf(cp, "NCOLS=%d\n", stdos.reclen);
				printheader(stdout, info);
			}
			if (stdos.reclen == 1)
				printresolu(stdout, xres, yres);
			if (waitflush > 0)
				fflush(stdout);
			stdos.xr = xres; stdos.yr = yres;
#ifdef getc_unlocked
			flockfile(stdout);	/* avoid lock/unlock overhead */
#endif
			using_stdout = 1;
		}
		stdos.ofp = stdout;
		stdos.reclen += noopen;
		return(&stdos);
	}
	ofl = ofname(oname, ospec, mname, bn);	/* get output name */
	if (ofl < 0) {
		sprintf(errmsg, "bad output format '%s'", ospec);
		error(USER, errmsg);
	}
	lep = lu_find(&ofiletab, oname);	/* look it up */
	if (lep->key == NULL)			/* new entry */
		lep->key = strcpy((char *)malloc(strlen(oname)+1), oname);
	sop = (STREAMOUT *)lep->data;
	if (sop == NULL) {			/* allocate stream */
		sop = (STREAMOUT *)malloc(sizeof(STREAMOUT));
		if (sop == NULL)
			error(SYSTEM, "out of memory in getostream");
		sop->outpipe = (oname[0] == '!');
		sop->reclen = 0;
		sop->ofp = NULL;		/* open iff noopen==0 */
		sop->xr = xres; sop->yr = yres;
		lep->data = (char *)sop;
		if (!sop->outpipe & !force_open & !recover &&
				access(oname, F_OK) == 0) {
			errno = EEXIST;		/* file exists */
			goto openerr;
		}
	} else if (noopen && outfmt == 'c' &&	/* stream exists to picture? */
			(sop->xr > 0) & (sop->yr > 0)) {
		if (ofl & OF_BIN)
			return(NULL);		/* let caller offset bins */
		sprintf(errmsg, "output '%s' not a valid picture", oname);
		error(WARNING, errmsg);
	}
	if (!noopen && sop->ofp == NULL) {	/* open output stream */
		if (oname[0] == '!')		/* output to command */
			sop->ofp = popen(oname+1, "w");
		else				/* else open file */
			sop->ofp = fopen(oname, "w");
		if (sop->ofp == NULL)
			goto openerr;
		if (outfmt != 'a')
			SET_FILE_BINARY(sop->ofp);
#ifdef getc_unlocked
		flockfile(sop->ofp);		/* avoid lock/unlock overhead */
#endif
		if (accumulate > 0) {		/* global resolution */
			sop->xr = xres; sop->yr = yres;
		}
		if (header) {
			cp = info;
			if (ofl & OF_MODIFIER || sop->reclen == 1) {
				sprintf(cp, "MODIFIER=%s\n", mname);
				while (*cp) ++cp;
			}
			if (ofl & OF_BIN) {
				sprintf(cp, "BIN=%d\n", bn);
				while (*cp) ++cp;
			}
			if (sop->yr > 0) {
				sprintf(cp, "NROWS=%d\n", sop->yr *
						(sop->xr + !sop->xr) );
				while (*cp) ++cp;
			}
			if ((sop->xr <= 0) | (sop->reclen > 1))
				sprintf(cp, "NCOLS=%d\n", sop->reclen);
			printheader(sop->ofp, info);
		}
		if (sop->reclen == 1)
			printresolu(sop->ofp, sop->xr, sop->yr);
		if (waitflush > 0)
			fflush(sop->ofp);
	}
	sop->reclen += noopen;			/* add to length if noopen */
	return(sop);				/* return output stream */
openerr:
	sprintf(errmsg, "cannot open '%s' for writing", oname);
	error(SYSTEM, errmsg);
	return(NULL);	/* pro forma return */
}
Example #15
0
void
nextstate(struct con *cp)
{
	if (match(cp->ibuf, "QUIT") && cp->state < 99) {
		snprintf(cp->obuf, cp->osize, "221 %s\r\n", hostname);
		cp->op = cp->obuf;
		cp->ol = strlen(cp->op);
		cp->w = t + cp->stutter;
		cp->laststate = cp->state;
		cp->state = 99;
		return;
	}

	if (match(cp->ibuf, "RSET") && cp->state > 2 && cp->state < 50) {
		snprintf(cp->obuf, cp->osize,
		    "250 Ok to start over.\r\n");
		cp->op = cp->obuf;
		cp->ol = strlen(cp->op);
		cp->w = t + cp->stutter;
		cp->laststate = cp->state;
		cp->state = 2;
		return;
	}
	switch (cp->state) {
	case 0:
		/* banner sent; wait for input */
		cp->ip = cp->ibuf;
		cp->il = sizeof(cp->ibuf) - 1;
		cp->laststate = cp->state;
		cp->state = 1;
		cp->r = t;
		break;
	case 1:
		/* received input: parse, and select next state */
		if (match(cp->ibuf, "HELO") ||
		    match(cp->ibuf, "EHLO")) {
			gethelo(cp->helo, sizeof cp->helo, cp->ibuf);
			snprintf(cp->obuf, cp->osize,
			    "250 Hello, spam sender. "
			    "Pleased to be wasting your time.\r\n");
			cp->op = cp->obuf;
			cp->ol = strlen(cp->op);
			cp->laststate = cp->state;
			cp->state = 2;
			cp->w = t + cp->stutter;
			break;
		}
		goto mail;
	case 2:
		/* sent 250 Hello, wait for input */
		cp->ip = cp->ibuf;
		cp->il = sizeof(cp->ibuf) - 1;
		cp->laststate = cp->state;
		cp->state = 3;
		cp->r = t;
		break;
	case 3:
	mail:
		if (match(cp->ibuf, "MAIL")) {
			setlog(cp->mail, sizeof cp->mail, cp->ibuf);
			snprintf(cp->obuf, cp->osize,
			    "250 You are about to try to deliver spam. "
			    "Your time will be spent, for nothing.\r\n");
			cp->op = cp->obuf;
			cp->ol = strlen(cp->op);
			cp->laststate = cp->state;
			cp->state = 4;
			cp->w = t + cp->stutter;
			break;
		}
		goto rcpt;
	case 4:
		/* sent 250 Sender ok */
		cp->ip = cp->ibuf;
		cp->il = sizeof(cp->ibuf) - 1;
		cp->laststate = cp->state;
		cp->state = 5;
		cp->r = t;
		break;
	case 5:
	rcpt:
		if (match(cp->ibuf, "RCPT")) {
			setlog(cp->rcpt, sizeof(cp->rcpt), cp->ibuf);
			snprintf(cp->obuf, cp->osize,
			    "250 This is hurting you more than it is "
			    "hurting me.\r\n");
			cp->op = cp->obuf;
			cp->ol = strlen(cp->op);
			cp->laststate = cp->state;
			cp->state = 6;
			cp->w = t + cp->stutter;
			if (cp->mail[0] && cp->rcpt[0]) {
				if (verbose)
					syslog_r(LOG_INFO, &sdata,
					    "(%s) %s: %s -> %s",
					    cp->blacklists ? "BLACK" : "GREY",
					    cp->addr, cp->mail,
					    cp->rcpt);
				if (debug)
					fprintf(stderr, "(%s) %s: %s -> %s\n",
					    cp->blacklists ? "BLACK" : "GREY",
					    cp->addr, cp->mail, cp->rcpt);
				if (greylist && cp->blacklists == NULL) {
					/* send this info to the greylister */
					getcaddr(cp);
					if (debug) /* XXX */
						fprintf(stderr,
					    "CO:%s\nHE:%s\nIP:%s\nFR:%s\nTO:%s\n",
					    cp->caddr, cp->helo, cp->addr,
					    cp->mail, cp->rcpt);
					fprintf(grey,
					    "CO:%s\nHE:%s\nIP:%s\nFR:%s\nTO:%s\n",
					    cp->caddr, cp->helo, cp->addr,
					    cp->mail, cp->rcpt);
					fflush(grey);
				}
			}
			break;
		}
		goto spam;
	case 6:
		/* sent 250 blah */
		cp->ip = cp->ibuf;
		cp->il = sizeof(cp->ibuf) - 1;
		cp->laststate = cp->state;
		cp->state = 5;
		cp->r = t;
		break;

	case 50:
	spam:
		if (match(cp->ibuf, "DATA")) {
			snprintf(cp->obuf, cp->osize,
			    "354 Enter spam, end with \".\" on a line by "
			    "itself\r\n");
			cp->state = 60;
			if (window && setsockopt(cp->fd, SOL_SOCKET, SO_RCVBUF,
			    &window, sizeof(window)) == -1) {
				syslog_r(LOG_DEBUG, &sdata,"setsockopt: %m");
				/* don't fail if this doesn't work. */
			}
			cp->ip = cp->ibuf;
			cp->il = sizeof(cp->ibuf) - 1;
			cp->op = cp->obuf;
			cp->ol = strlen(cp->op);
			cp->w = t + cp->stutter;
			if (greylist && cp->blacklists == NULL) {
				cp->laststate = cp->state;
				cp->state = 98;
				goto done;
			}
		} else {
			if (match(cp->ibuf, "NOOP")) 
				snprintf(cp->obuf, cp->osize,
				    "250 2.0.0 OK I did nothing\r\n");
			else
                        	snprintf(cp->obuf, cp->osize,
				    "500 5.5.1 Command unrecognized\r\n");
			cp->state = cp->laststate;
			cp->ip = cp->ibuf;
			cp->il = sizeof(cp->ibuf) - 1;
			cp->op = cp->obuf;
			cp->ol = strlen(cp->op);
			cp->w = t + cp->stutter;
		}
		break;
	case 60:
		/* sent 354 blah */
		cp->ip = cp->ibuf;
		cp->il = sizeof(cp->ibuf) - 1;
		cp->laststate = cp->state;
		cp->state = 70;
		cp->r = t;
		break;
	case 70: {
		char *p, *q;

		for (p = q = cp->ibuf; q <= cp->ip; ++q)
			if (*q == '\n' || q == cp->ip) {
				*q = 0;
				if (q > p && q[-1] == '\r')
					q[-1] = 0;
				if (!strcmp(p, ".") ||
				    (cp->data_body && ++cp->data_lines >= 10)) {
					cp->laststate = cp->state;
					cp->state = 98;
					goto done;
				}
				if (!cp->data_body && !*p)
					cp->data_body = 1;
				if (verbose && cp->data_body && *p)
					syslog_r(LOG_DEBUG, &sdata, "%s: "
					    "Body: %s", cp->addr, p);
				else if (verbose && (match(p, "FROM:") ||
				    match(p, "TO:") || match(p, "SUBJECT:")))
					syslog_r(LOG_INFO, &sdata, "%s: %s",
					    cp->addr, p);
				p = ++q;
			}
		cp->ip = cp->ibuf;
		cp->il = sizeof(cp->ibuf) - 1;
		cp->r = t;
		break;
	}
	case 98:
	done:
		doreply(cp);
		cp->op = cp->obuf;
		cp->ol = strlen(cp->op);
		cp->w = t + cp->stutter;
		cp->laststate = cp->state;
		cp->state = 99;
		break;
	case 99:
		closecon(cp);
		break;
	default:
		errx(1, "illegal state %d", cp->state);
		break;
	}
}
Example #16
0
/* ---------------------------------------------------------------------- */
void
print_extra_info()
{
  int rc = 0;
#ifdef HAVE_IFCONFIG
  printf("ifconfig output:\n");
  fflush(stdout);
  fflush(stderr);
  rc = system("/sbin/ifconfig");
  fflush(stdout);
  fflush(stderr);
  printf("-----------------------------------------------\n");
#endif /* HAVE_IFCONFIG */

#ifdef HAVE_PROC_FILE_INFO
  do_proc_info("/proc/version");
  do_proc_info("/proc/sys/kernel/rtsig-max");
  do_proc_info("/proc/sys/fs/file-max");
  do_proc_info("/proc/sys/net/ipv4/tcp_max_syn_backlog");
  do_proc_info("/proc/sys/net/ipv4/ip_local_port_range");
  do_proc_info("/proc/sys/net/ipv4/tcp_tw_recycle");
  do_proc_info("/proc/sys/net/ipv4/tcp_max_tw_buckets");
  do_proc_info("/proc/sys/net/ipv4/tcp_fin_timeout");
  do_proc_info("/proc/sys/net/ipv4/tcp_abort_on_overflow");
  do_proc_info("/proc/sys/net/core/somaxconn");

  fflush(stdout);
  fflush(stderr);
  printf("From /proc/cpuinfo:\n");
  fflush(stdout);
  fflush(stderr);
  rc = system("egrep 'model name|processor|MHz|cache|_id' /proc/cpuinfo");
  fflush(stdout);
  fflush(stderr);

  printf("From /proc/interrupts (before):\n");
  rc = system("grep 'eth' /proc/interrupts");

#endif /* HAVE_PROC_FILE_INFO */

#ifdef HAVE_LIMITS
  printf("-----------------------------------------------\n");
  printf("Limits:\n");
  fflush(stdout);
  fflush(stderr);
  rc = system("csh -c limit");
  fflush(stdout);
  fflush(stderr);
  printf("-----------------------------------------------\n");
  fflush(stdout);
  fflush(stderr);
#endif /* HAVE_LIMITS */
}
Example #17
0
int main()
{
	criarTabuleiro();
	mostrarTabuleiro();

	Player jogo = NULL;

	int turno = 1;
	int fim = 0;
	int x0, y0, xf, yf, jAtual = 0;
	char jogador1[10], jogador2[10], jogadorAtual[10];


	puts(" ");
	do
	{
		if (turno == 1) {
			printf("=== JOGADOR 1 insira o nome ===\n");
			scanf("%s", jogador1);
			printf("=== JOGADOR 2 insira o nome ===\n");
			scanf("%s", jogador2);
			
			system("cls");
			fflush(stdin);
		}

		strcpy(jogadorAtual, jogador1);

		if (jAtual > 2) {
			strcpy(jogadorAtual, jogador1);
			jAtual = 0;
		}
		if (jAtual == 1)
			strcpy(jogadorAtual, jogador2);

		printf("======================================================\n");
		printf("TURNO: %d\nJOGADOR: %s", turno, jogadorAtual);
		puts(" ");
		mostrarTabuleiro();

		printf("==== Insira um movimento ===\n");
		printf("\t ESCOLHA A CORDENADA DA PEÇA A MOVIMENTAR [x0, y0]\n");
		printf("\t x0 = \n");
		scanf("%d", &x0);
		printf("\t y0 = \n");
		scanf("%d", &y0);
		printf("\t ESCOLHA A CORDENADA O DESTINO DA PEÇA [xf, yf]");

		scanf("%d %d", &xf, &yf);
		fflush(stdin);

		//fazerMovimento(x0)
		turno++;

		mostrarTabuleiro();
		printf("FIM DE JOGADA ? [1-sim, 0-não]\n");
		scanf("%d", &fim);

		fflush(stdin);
		jAtual++;

		if (vencerPartida() == 1)
		{
			system("cls");
			printf("PARABéNS O JOGADOR 1 VENCEU A PARTIDA!!!");
			break;
		}
		if (vencerPartida() == 2)
		{
			system("cls");
			printf("PARABéNS O JOGADOR 2 VENCEU A PARTIDA!!!");
			break;
		}

	} while (vencerPartida() == 0);


	getchar();
	return 0;
}
Example #18
0
int main(int argc, char *argv[]) {
        int r;
        Hashmap *a = NULL, *b = NULL;
        unsigned iteration = 0;
        usec_t last_refresh = 0;
        bool quit = false, immediate_refresh = false;

        log_parse_environment();
        log_open();

        r = parse_argv(argc, argv);
        if (r <= 0)
                goto finish;

        a = hashmap_new(string_hash_func, string_compare_func);
        b = hashmap_new(string_hash_func, string_compare_func);
        if (!a || !b) {
                r = log_oom();
                goto finish;
        }

        signal(SIGWINCH, columns_lines_cache_reset);

        if (!on_tty())
                arg_iterations = 1;

        while (!quit) {
                Hashmap *c;
                usec_t t;
                char key;
                char h[FORMAT_TIMESPAN_MAX];

                t = now(CLOCK_MONOTONIC);

                if (t >= last_refresh + arg_delay || immediate_refresh) {

                        r = refresh(a, b, iteration++);
                        if (r < 0)
                                goto finish;

                        group_hashmap_clear(b);

                        c = a;
                        a = b;
                        b = c;

                        last_refresh = t;
                        immediate_refresh = false;
                }

                r = display(b);
                if (r < 0)
                        goto finish;

                if (arg_iterations && iteration >= arg_iterations)
                        break;

                if (arg_batch) {
                        usleep(last_refresh + arg_delay - t);
                } else {
                        r = read_one_char(stdin, &key,
                                          last_refresh + arg_delay - t, NULL);
                        if (r == -ETIMEDOUT)
                                continue;
                        if (r < 0) {
                                log_error("Couldn't read key: %s", strerror(-r));
                                goto finish;
                        }
                }

                fputs("\r \r", stdout);
                fflush(stdout);

                if (arg_batch)
                        continue;

                switch (key) {

                case ' ':
                        immediate_refresh = true;
                        break;

                case 'q':
                        quit = true;
                        break;

                case 'p':
                        arg_order = ORDER_PATH;
                        break;

                case 't':
                        arg_order = ORDER_TASKS;
                        break;

                case 'c':
                        arg_order = ORDER_CPU;
                        break;

                case 'm':
                        arg_order = ORDER_MEMORY;
                        break;

                case 'i':
                        arg_order = ORDER_IO;
                        break;

                case '%':
                        arg_cpu_type = arg_cpu_type == CPU_TIME ? CPU_PERCENT : CPU_TIME;
                        break;

                case '+':
                        if (arg_delay < USEC_PER_SEC)
                                arg_delay += USEC_PER_MSEC*250;
                        else
                                arg_delay += USEC_PER_SEC;

                        fprintf(stdout, "\nIncreased delay to %s.", format_timespan(h, sizeof(h), arg_delay, 0));
                        fflush(stdout);
                        sleep(1);
                        break;

                case '-':
                        if (arg_delay <= USEC_PER_MSEC*500)
                                arg_delay = USEC_PER_MSEC*250;
                        else if (arg_delay < USEC_PER_MSEC*1250)
                                arg_delay -= USEC_PER_MSEC*250;
                        else
                                arg_delay -= USEC_PER_SEC;

                        fprintf(stdout, "\nDecreased delay to %s.", format_timespan(h, sizeof(h), arg_delay, 0));
                        fflush(stdout);
                        sleep(1);
                        break;

                case '?':
                case 'h':
                        fprintf(stdout,
                                "\t<" ON "P" OFF "> By path; <" ON "T" OFF "> By tasks; <" ON "C" OFF "> By CPU; <" ON "M" OFF "> By memory; <" ON "I" OFF "> By I/O\n"
                                "\t<" ON "+" OFF "> Increase delay; <" ON "-" OFF "> Decrease delay; <" ON "%%" OFF "> Toggle time\n"
                                "\t<" ON "Q" OFF "> Quit; <" ON "SPACE" OFF "> Refresh");
                        fflush(stdout);
                        sleep(3);
                        break;

                default:
                        fprintf(stdout, "\nUnknown key '%c'. Ignoring.", key);
                        fflush(stdout);
                        sleep(1);
                        break;
                }
        }

        r = 0;

finish:
        group_hashmap_free(a);
        group_hashmap_free(b);

        if (r < 0) {
                log_error("Exiting with failure: %s", strerror(-r));
                return EXIT_FAILURE;
        }

        return EXIT_SUCCESS;
}
Example #19
0
int log__vprintf(int priority, const char *fmt, va_list va)
{
	char *s;
	char *st;
	int len;
#ifdef WIN32
	char *sp;
#endif
	const char *topic;
	int syslog_priority;
	time_t now = time(NULL);
	static time_t last_flush = 0;

	if((log_priorities & priority) && log_destinations != MQTT3_LOG_NONE){
		switch(priority){
			case MOSQ_LOG_SUBSCRIBE:
				topic = "$SYS/broker/log/M/subscribe";
#ifndef WIN32
				syslog_priority = LOG_NOTICE;
#else
				syslog_priority = EVENTLOG_INFORMATION_TYPE;
#endif
				break;
			case MOSQ_LOG_UNSUBSCRIBE:
				topic = "$SYS/broker/log/M/unsubscribe";
#ifndef WIN32
				syslog_priority = LOG_NOTICE;
#else
				syslog_priority = EVENTLOG_INFORMATION_TYPE;
#endif
				break;
			case MOSQ_LOG_DEBUG:
				topic = "$SYS/broker/log/D";
#ifndef WIN32
				syslog_priority = LOG_DEBUG;
#else
				syslog_priority = EVENTLOG_INFORMATION_TYPE;
#endif
				break;
			case MOSQ_LOG_ERR:
				topic = "$SYS/broker/log/E";
#ifndef WIN32
				syslog_priority = LOG_ERR;
#else
				syslog_priority = EVENTLOG_ERROR_TYPE;
#endif
				break;
			case MOSQ_LOG_WARNING:
				topic = "$SYS/broker/log/W";
#ifndef WIN32
				syslog_priority = LOG_WARNING;
#else
				syslog_priority = EVENTLOG_WARNING_TYPE;
#endif
				break;
			case MOSQ_LOG_NOTICE:
				topic = "$SYS/broker/log/N";
#ifndef WIN32
				syslog_priority = LOG_NOTICE;
#else
				syslog_priority = EVENTLOG_INFORMATION_TYPE;
#endif
				break;
			case MOSQ_LOG_INFO:
				topic = "$SYS/broker/log/I";
#ifndef WIN32
				syslog_priority = LOG_INFO;
#else
				syslog_priority = EVENTLOG_INFORMATION_TYPE;
#endif
				break;
#ifdef WITH_WEBSOCKETS
			case MOSQ_LOG_WEBSOCKETS:
				topic = "$SYS/broker/log/WS";
#ifndef WIN32
				syslog_priority = LOG_DEBUG;
#else
				syslog_priority = EVENTLOG_INFORMATION_TYPE;
#endif
				break;
#endif
			default:
				topic = "$SYS/broker/log/E";
#ifndef WIN32
				syslog_priority = LOG_ERR;
#else
				syslog_priority = EVENTLOG_ERROR_TYPE;
#endif
		}
		len = strlen(fmt) + 500;
		s = mosquitto__malloc(len*sizeof(char));
		if(!s) return MOSQ_ERR_NOMEM;

		vsnprintf(s, len, fmt, va);
		s[len-1] = '\0'; /* Ensure string is null terminated. */

		if(log_destinations & MQTT3_LOG_STDOUT){
			if(int_db.config && int_db.config->log_timestamp){
				fprintf(stdout, "%d: %s\n", (int)now, s);
			}else{
				fprintf(stdout, "%s\n", s);
			}
			fflush(stdout);
		}
		if(log_destinations & MQTT3_LOG_STDERR){
			if(int_db.config && int_db.config->log_timestamp){
				fprintf(stderr, "%d: %s\n", (int)now, s);
			}else{
				fprintf(stderr, "%s\n", s);
			}
			fflush(stderr);
		}
		if(log_destinations & MQTT3_LOG_FILE && int_db.config->log_fptr){
			if(int_db.config && int_db.config->log_timestamp){
				fprintf(int_db.config->log_fptr, "%d: %s\n", (int)now, s);
			}else{
				fprintf(int_db.config->log_fptr, "%s\n", s);
			}
			if(now - last_flush > 1){
				fflush(int_db.config->log_fptr);
				last_flush = now;
			}
		}
		if(log_destinations & MQTT3_LOG_SYSLOG){
#ifndef WIN32
			syslog(syslog_priority, "%s", s);
#else
			sp = (char *)s;
			ReportEvent(syslog_h, syslog_priority, 0, 0, NULL, 1, 0, &sp, NULL);
#endif
		}
		if(log_destinations & MQTT3_LOG_TOPIC && priority != MOSQ_LOG_DEBUG){
			if(int_db.config && int_db.config->log_timestamp){
				len += 30;
				st = mosquitto__malloc(len*sizeof(char));
				if(!st){
					mosquitto__free(s);
					return MOSQ_ERR_NOMEM;
				}
				snprintf(st, len, "%d: %s", (int)now, s);
				db__messages_easy_queue(&int_db, NULL, topic, 2, strlen(st), st, 0);
				mosquitto__free(st);
			}else{
				db__messages_easy_queue(&int_db, NULL, topic, 2, strlen(s), s, 0);
			}
		}
		mosquitto__free(s);
	}

	return MOSQ_ERR_SUCCESS;
}
Example #20
0
static void kraise_splice (char *file1, char *file2, char *fileout) {

  kr_mkv_t *in[2];
  kr_mkv_t *out;
  int i;
  int bytes_read;
  uint32_t track;
  uint64_t timecode;
  uint8_t *buffer[2];
  uint32_t out_track;
  int keyframe;
  uint8_t flags;
  int packets;
  int have_buffer[2];
  int have_buffer_bytes[2];
  int inframes;

  have_buffer_bytes[0] = 0;
  have_buffer_bytes[1] = 0;
  have_buffer[1] = 0;
  inframes = 0;
  have_buffer[0] = 0;
  have_buffer[1] = 0;
  packets = 0;

  buffer[0] = malloc (10000000);
  buffer[1] = malloc (10000000);

  for (i = 0; i < 2; i++) {

    if (i == 0) {
      in[i] = kr_mkv_open_file (file1);
    } else {
      in[i] = kr_mkv_open_file (file2);
    }


    printf ("File %d: FPS %d/%d RES %dx%d\n",
            i,
            in[i]->tracks[VIDEO_TRACK].fps_numerator,
            in[i]->tracks[VIDEO_TRACK].fps_denominator,
            in[i]->tracks[VIDEO_TRACK].width,
            in[i]->tracks[VIDEO_TRACK].height);

    if (in[0] == NULL) {
      fprintf (stderr, "Could not open input file: %s\n", file1);
      exit (1);
    }
  }


  if ((in[0]->tracks[VIDEO_TRACK].width != in[0]->tracks[VIDEO_TRACK].width) ||
      (in[1]->tracks[VIDEO_TRACK].height != in[1]->tracks[VIDEO_TRACK].height)) {

    fprintf (stderr, "Resolutions are not equal\n");
    exit (1);
  }


  out = kr_mkv_create_file (fileout);

  if (out == NULL) {
    fprintf (stderr, "Could not open output file: %s\n", fileout);
    exit (1);
  }

  printf ("Created file: %s\n", fileout);

  out_track = kr_mkv_add_video_track (out, VP8,
                                     30,
                                     1,
                                     in[0]->tracks[VIDEO_TRACK].width,
                                     in[0]->tracks[VIDEO_TRACK].height);

  printf ("Added new track: %d\n", out_track);




  while ((bytes_read = kr_mkv_read_packet (in[0], &track, &timecode, &flags, buffer[0])) > 0) {

    have_buffer_bytes[0] = bytes_read;

    printf ("Read file %d packet %d track %d %d bytes\n",
            1, packets++, track, bytes_read);
    fflush (stdout);

    if (flags == 0x80) {
      keyframe = 1;
    } else {
      keyframe = 0;
    }

    if (keyframe == 1) {
      inframes = 0;
      while ((have_buffer[1] == 1) ||
             (((bytes_read = kr_mkv_read_packet (in[1], &track, &timecode, &flags, buffer[1])) > 0))) {

        if (have_buffer[1] == 1) {
          keyframe = 1;
          have_buffer[1] = 0;
        } else {
          printf ("Read file %d packet %d track %d %d bytes\n",
                  2, packets++, track, bytes_read);
          fflush (stdout);

          if (flags == 0x80) {
            keyframe = 1;
          } else {
            keyframe = 0;
          }

          have_buffer_bytes[1] = bytes_read;

          if ((keyframe == 1) && (inframes > 0)) {
            have_buffer[1] = 1;
            break;
          }
        }
        if (track == 1) {
          kr_mkv_add_video (out, out_track, buffer[1], have_buffer_bytes[1], keyframe);
        }
        inframes++;
      }
    }

    if (track == 1) {
      kr_mkv_add_video (out, out_track, buffer[0], have_buffer_bytes[0], keyframe);
    }
  }

  printf ("\nDone.\n");

  free (buffer[0]);
  free (buffer[1]);
  kr_mkv_destroy (&in[0]);
  kr_mkv_destroy (&in[1]);
  kr_mkv_destroy (&out);

}
Example #21
0
File: bcp.c Project: Cacauu/cups
int					/* O - Exit status */
main(int  argc,				/* I - Number of command-line args */
     char *argv[])			/* I - Command-line arguments */
{
  FILE		*fp;			/* File to print */
  int		copies;			/* Number of copies left */
  char		line[1024];		/* Line/buffer from stream/file */
  size_t	linelen;		/* Length of line */
  ppd_file_t	*ppd;			/* PPD file */


 /*
  * Check command-line...
  */

  if (argc < 6 || argc > 7)
  {
    _cupsLangPrintf(stderr,
                    _("Usage: %s job-id user title copies options [file]"),
		    argv[0]);
    return (1);
  }

  if (argc == 6)
  {
    copies = 1;
    fp     = stdin;
  }
  else
  {
    copies = atoi(argv[4]);
    fp     = fopen(argv[6], "rb");

    if (!fp)
    {
      perror(argv[6]);
      return (1);
    }
  }

 /*
  * Open the PPD file as needed...
  */

  ppd = ppdOpenFile(getenv("PPD"));

 /*
  * Copy the print file to stdout...
  */

  while (copies > 0)
  {
    copies --;

    if (ppd && ppd->jcl_begin)
      fputs(ppd->jcl_begin, stdout);
    if (ppd && ppd->jcl_ps)
      fputs(ppd->jcl_ps, stdout);

    if (!ppd || ppd->language_level == 1)
    {
     /*
      * Use setsoftwareiomode for BCP mode...
      */

      puts("%!PS-Adobe-3.0 ExitServer");
      puts("%%Title: (BCP - Level 1)");
      puts("%%EndComments");
      puts("%%BeginExitServer: 0");
      puts("serverdict begin 0 exitserver");
      puts("%%EndExitServer");
      puts("statusdict begin");
      puts("/setsoftwareiomode known {100 setsoftwareiomode}");
      puts("end");
      puts("%EOF");
    }
    else
    {
     /*
      * Use setdevparams for BCP mode...
      */

      puts("%!PS-Adobe-3.0");
      puts("%%Title: (BCP - Level 2)");
      puts("%%EndComments");
      puts("currentsysparams");
      puts("/CurInputDevice 2 copy known {");
      puts("get");
      puts("<</Protocol /Binary>> setdevparams");
      puts("}{");
      puts("pop pop");
      puts("} ifelse");
      puts("%EOF");
    }

    if (ppd && ppd->jcl_end)
      fputs(ppd->jcl_end, stdout);
    else if (!ppd || ppd->num_filters == 0)
      putchar(0x04);

   /*
    * Loop until we see end-of-file...
    */

    do
    {
      linelen = sizeof(line);
      if (psgets(line, &linelen, fp) == NULL)
	break;
    }
    while (pswrite(line, linelen) > 0);

    fflush(stdout);
  }

  return (0);
}
Example #22
0
//------------------------------------------------------------------------------
const char * TExec::Abrir(const char * nomeprog)
{
    if (Rodando)
        return "Já está rodando um programa";
    FecharPipe();

    while (*nomeprog == ' ')
        nomeprog++;
    if (*nomeprog == 0)
        return "Arquivo não existe";

#ifdef __WIN32__
    BOOL Success;
    HANDLE descrpipe[4];

// Prepara estrutura SECURITY_ATTRIBUTES
    memset(&SecurityAttributes, 0, sizeof(SecurityAttributes));
    SecurityAttributes.nLength              = sizeof(SECURITY_ATTRIBUTES);
    SecurityAttributes.bInheritHandle       = TRUE;
    SecurityAttributes.lpSecurityDescriptor = NULL;

// Cria pipe de entrada (STDOUT do programa)
    Success = CreatePipe(descrpipe, // Handle de leitura
                         descrpipe+1, // Handle de escrita
                         &SecurityAttributes, // Atributos de segurança
                         0); // Número de bytes reservado para o pipe, 0=default
    if (!Success)
        return "Erro ao criar PIPE";

// Cria pipe de saída (STDIN do programa)
    Success = CreatePipe(descrpipe+2, // Handle de leitura
                         descrpipe+3, // Handle de escrita
                         &SecurityAttributes, // Atributos de segurança
                         0); // Número de bytes reservado para o pipe, 0=default
    if (!Success)
    {
        CloseHandle(descrpipe[0]);
        CloseHandle(descrpipe[1]);
        return "Erro ao criar PIPE";
    }

    DWORD dwMode = PIPE_READMODE_MESSAGE | PIPE_NOWAIT;
    Success = SetNamedPipeHandleState(
        descrpipe[3],   // Handle de leitura
        &dwMode,        // Modo do pipe
        NULL,           // don't set maximum bytes
        NULL);          // don't set maximum time

// Prepara estrutura STARTUPINFO
    memset(&StartupInfo, 0, sizeof(StartupInfo));
    StartupInfo.cb           = sizeof(STARTUPINFO);
    StartupInfo.dwFlags      = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
    //StartupInfo.dwFlags      = STARTF_USESTDHANDLES;
    StartupInfo.wShowWindow  = SW_HIDE;
    StartupInfo.hStdInput    = descrpipe[2];
    StartupInfo.hStdOutput   = descrpipe[1];
    StartupInfo.hStdError    = descrpipe[1];

// Cria processo filho
    memset(&ProcessInfo, 0, sizeof(ProcessInfo));
    Success = CreateProcess(
            NULL,             // Nome do módulo executável, pode ser NULL
            LPTSTR(nomeprog), // Linha de comando (nota: na versão unicode não deve ser const)
            NULL,             // Atributos de segurança
            NULL,             // Atributos de segurança de thread
            TRUE,             // Herda handles
            DETACHED_PROCESS, // Flags de criação e prioridade do processo
            NULL,             // Variáveis de ambiente
            NULL,             // Diretório do programa
            &StartupInfo,     // Estrutura STARTUPINFO
            &ProcessInfo);    // Estrutura PROCESS_INFORMATION
    if ( !Success )
    {
        DWORD dw = GetLastError();
        CloseHandle(descrpipe[0]);
        CloseHandle(descrpipe[1]);
        CloseHandle(descrpipe[2]);
        CloseHandle(descrpipe[3]);
        switch (dw)
        {
        case ERROR_FILE_NOT_FOUND: return "Arquivo não encontrado";
        case ERROR_PATH_NOT_FOUND: return "Caminho não encontrado";
        case ERROR_ACCESS_DENIED:
            return "Acesso negado";
        case ERROR_INVALID_EXE_SIGNATURE:
        case ERROR_EXE_MARKED_INVALID:
            return "Não é possível rodar o programa";
        case ERROR_BAD_EXE_FORMAT:
            return "Arquivo não é um aplicativo Win32 válido";
        case ERROR_EXE_MACHINE_TYPE_MISMATCH:
            return "Programa não é compatível com a sua versão do Windows";
        }
        return "Erro ao executar programa";
    }

// Acerta variáveis
    pipe_in = descrpipe[0];// Entrada
    CloseHandle(descrpipe[1]);
    CloseHandle(descrpipe[2]);    // Saída
    pipe_out = descrpipe[3];

    Rodando = true;
    return 0;

#else

// Obtém os argumentos
    int argc = 0;
    char * argv[20];
    char argtxt[1024];

    char * d = argtxt;
    char * dmax = argtxt + sizeof(argtxt);
    argv[argc++] = d;

    for (; d<dmax; nomeprog++)
    {
        // Encontrou barra invertida
        //     Copia o próximo caracter
        if (*nomeprog == '\\')
        {
            if (nomeprog[1] == 0)
                continue;
            nomeprog += 1;
            *d++ = *nomeprog;
            continue;
        }
        // Encontrou aspas
        //     Copia texto até encontrar aspas novamente
        //     Exceto se encontrar \"  aí considera aspas
        if (*nomeprog == '\"')
        {
            nomeprog++;
            while (*nomeprog && *nomeprog!='\"' && d<dmax)
            {
                if (nomeprog[0] == '\\')
                    if (nomeprog[1] == '\"')
                        nomeprog++;
                *d++=nomeprog[0], nomeprog++;
            }
            continue;
        }
        // Encontrou espaço ou fim do texto
        //     Passa para o próximo argumento
        //     Avança enquanto houver espaço
        if (*nomeprog == ' ' || *nomeprog == 0)
        {
            *d++ = 0;
            while (*nomeprog == ' ')
                nomeprog++;
            if (argc >= 19 || *nomeprog == 0)
                break;
            argv[argc++] = d;
            nomeprog--;
            continue;
        }

        *d++ = *nomeprog;
    }
    if (d >= dmax)
        return "Comando muito grande";
    argv[argc] = 0;

// Obtém o nome do executável
    char nomebuf[256];
    const char * nomearq = argv[0];

    if (*nomearq == 0)
        return "Arquivo não existe";
    if (strchr(nomearq, '/'))
    {
        if (access(nomearq, X_OK) < 0)
            nomearq = 0;
    }
    else
    {
        int nometam = strlen(nomearq);
        const char * path = getenv("PATH");
        if (path == 0)
            path = "/bin:/usr/bin";
        while (true)
        {
            if (*path == 0)
                return "Arquivo não existe";
            int pathtam = 0;
            const char * p = path;
            while (*path && *path != ':')
                path++;
            if (p == path)
                pathtam = 1, p=".";
            else
                pathtam = path-p;
            if (*path == ':')
                path++;
            if (pathtam + nometam + 2 > (int)sizeof(nomebuf))
                continue;
            memcpy(nomebuf, p, pathtam);
            nomebuf[pathtam] = '/';
            memcpy(nomebuf + pathtam + 1, nomearq, nometam);
            nomebuf[pathtam + nometam + 1] = 0;
            if (access(nomebuf, X_OK) < 0)
                continue;
            nomearq = nomebuf;
            break;
        }
    }

#if 0
    // Mostra o nome do programa e os argumentos
    printf(">%s\n", nomearq);
    for (int x=0; argv[x]; x++)
        printf(">%s\n", argv[x]);
    fflush(stdout);
#endif

// Cria pipe
    int descrpipe[4];
    if (pipe(descrpipe)<0)      // Cria "pipe" de entrada
        return "Erro ao criar PIPE";
    if (pipe(descrpipe+2)<0)    // Cria "pipe" de saída
    {
        close(descrpipe[0]);
        close(descrpipe[1]);
        return "Erro ao criar PIPE";
    }

// Cria processo e executa programa
    char ch;
    pid = fork();               // Cria novo processo
    if (pid<0)                  // Se <0: ocorreu erro
    {
        close(descrpipe[0]);    // Entrada
        close(descrpipe[1]);
        close(descrpipe[2]);    // Saída
        close(descrpipe[3]);
        return "Erro ao criar processo";
    }
    if (pid>0)                  // Se >0: processo "pai"
    {
        pipe_in = descrpipe[0];// Entrada
        close(descrpipe[1]);
        close(descrpipe[2]);    // Saída
        pipe_out = descrpipe[3];
        read(pipe_in, &ch, 1); // Sincroniza com processo filho
        fcntl(pipe_in, F_SETFL, O_NONBLOCK);
        fcntl(pipe_out, F_SETFL, O_NONBLOCK);
        write(pipe_out, "a", 1);
        Rodando = true;
        return 0;
    }
    dup2(descrpipe[1],STDOUT_FILENO); // Entrada deste programa: stdout do outro
    dup2(descrpipe[1],STDERR_FILENO);
    dup2(descrpipe[2],STDIN_FILENO);  // Saída deste programa: stdin do outro
    close(descrpipe[0]);
    close(descrpipe[1]);
    close(descrpipe[2]);
    close(descrpipe[3]);
    signal(SIGPIPE,SIG_DFL);    // Acerta sinais
    signal(SIGCHLD,SIG_DFL);
    write(STDOUT_FILENO, "a", 1); // Sincroniza com processo pai
    read(STDIN_FILENO, &ch, 1);   // Lê um dado

// Executa programa
    execv(nomearq, argv);
    _exit(EXIT_FAILURE);
#endif
}
Example #23
0
void* serve_client(void* info)
{
	int sfd_client, connection_id, x;
	struct packet shp;
	char lpwd[LENBUFFER];
	struct client_info* ci = (struct client_info*) info;
	sfd_client = ci->sfd;
	connection_id = ci->cid;
	
	while(1)
	{
		if(recv_packet_ret(sfd_client, &shp) < 0)
		{
			fprintf(stderr, "client ID(%d) closed/terminated. closing connection.\n", connection_id);
			break;
		}

		if(shp.type == TERM)
			break;

		if(shp.conid == -1)
			shp.conid = connection_id;
		
		if(shp.type == REQU)
		{
			switch(shp.comid)
			{
				case PWD:
					if(!getcwd(lpwd, sizeof lpwd))
						er("getcwd()", 0);
					command_pwd(sfd_client, &shp, lpwd);
					break;
				case CD:
					if((x = chdir(shp.buffer)) == -1)
						fprintf(stderr, "Wrong path.\n");
					command_cd(sfd_client, &shp, x == -1 ? "fail" : "success");
					break;
				case MKDIR:
					command_mkdir(sfd_client, &shp);
					break;
				case LS:
					if(!getcwd(lpwd, sizeof lpwd))
						er("getcwd()", 0);
					command_ls(sfd_client, &shp, lpwd);
					break;
				case GET:
					command_get(sfd_client, &shp);
					break;
				case PUT:
					command_put(sfd_client, &shp);
					break;
				case RGET:
					if(!getcwd(lpwd, sizeof lpwd))
						er("getcwd()", 0);
					command_rget(sfd_client, &shp);
					send_EOT(sfd_client, &shp);
					if((x = chdir(lpwd)) == -1)
						fprintf(stderr, "Wrong path.\n");
					break;
				default:
					// print error
					break;
			}
		}
		else
		{
			//show error, send TERM and break
			fprintf(stderr, "packet incomprihensible. closing connection.\n");
			send_TERM(sfd_client, &shp);
			break;
		}
	}

	close(sfd_client);
	fflush(stdout);
	return NULL;
}
Example #24
0
static int show_help(const char *filename, const char *topic,
                     const char *output, orte_process_name_t *sender)
{
    int rc;
    tuple_list_item_t *tli = NULL;
    orte_namelist_t *pnli;
    time_t now = time(NULL);

    /* If we're aggregating, check for duplicates.  Otherwise, don't
       track duplicates at all and always display the message. */
    if (orte_help_want_aggregate) {
        rc = get_tli(filename, topic, &tli);
    } else {
        rc = ORTE_ERR_NOT_FOUND;
    }

    /* Was it already displayed? */
    if (ORTE_SUCCESS == rc) {
        /* Yes.  But do we want to print anything?  That's complicated.

           We always show the first message of a given (filename,
           topic) tuple as soon as it arrives.  But we don't want to
           show duplicate notices often, because we could get overrun
           with them.  So we want to gather them up and say "We got N
           duplicates" every once in a while.

           And keep in mind that at termination, we'll unconditionally
           show all accumulated duplicate notices.

           A simple scheme is as follows:
           - when the first of a (filename, topic) tuple arrives
             - print the message
             - if a timer is not set, set T=now
           - when a duplicate (filename, topic) tuple arrives
             - if now>(T+5) and timer is not set (due to
               non-pre-emptiveness of our libevent, a timer *could* be
               set!)
               - print all accumulated duplicates
               - reset T=now
             - else if a timer was not set, set the timer for T+5
             - else if a timer was set, do nothing (just wait)
           - set T=now when the timer expires
        */
        ++tli->tli_count_since_last_display;
        if (now > show_help_time_last_displayed + 5 && !show_help_timer_set) {
            show_accumulated_duplicates(0, 0, NULL);
        } else if (!show_help_timer_set) {
            opal_evtimer_set(&show_help_timer_event,
                             show_accumulated_duplicates, NULL);
            opal_evtimer_add(&show_help_timer_event, &show_help_interval);
            show_help_timer_set = true;
        }
    }
    /* Not already displayed */
    else if (ORTE_ERR_NOT_FOUND == rc) {
        if (orte_xml_output) {
            char *tmp;
            tmp = xml_format((unsigned char*)output);
            fprintf(orte_xml_fp, "%s", tmp);
            fflush(orte_xml_fp);
            free(tmp);
        } else {
            fprintf(stderr, "%s", output);
        }
        if (!show_help_timer_set) {
            show_help_time_last_displayed = now;
        }
    }
    /* Some other error occurred */
    else {
        ORTE_ERROR_LOG(rc);
        return rc;
    }

    /* If we're aggregating, add this process name to the list */
    if (orte_help_want_aggregate) {
        pnli = OBJ_NEW(orte_namelist_t);
        if (NULL == pnli) {
            rc = ORTE_ERR_OUT_OF_RESOURCE;
            ORTE_ERROR_LOG(rc);
            return rc;
        }
        pnli->name = *sender;
        opal_list_append(&(tli->tli_processes), &(pnli->item));
    }
    return ORTE_SUCCESS;
}
Example #25
0
int main(int argc, char **argv)
{
	int force = 0, lsock, csock, one = 0, jeden = 1, local_port;
	int detach = 1, sa_len, conn_limit = 0, optc;
	char *username = NULL, *bind_host = NULL;
	struct sockaddr *sa;
	struct sockaddr_in laddr, caddr;
	struct sockaddr_in6 laddr6;
	unsigned int caddrlen = sizeof(caddr);
	struct passwd *pw = NULL;
	
	while ((optc = getopt(argc, argv, "1dv46fHs:l:I:i:hu:m:L:A:p:")) != -1) {
		switch (optc) {
			case '1':
				one = 1;
				break;
			case 'd':
				detach = 0;
				break;
			case 'v':
				verbose = 1;
				break;
			case '4':
				break;
			case '6':
				remote_hint = AF_INET;
				local_hint = AF_INET6;
				break;
			case 's':
				source_host = xstrdup(optarg);
				break;
			case 'l':
				bind_host = xstrdup(optarg);
				break;
			case 'r':
				force = 1;
				break;
			case 'i':
				ircpass = xstrdup(optarg);
				clear_argv(argv[optind - 1]);
				break;
			case 'I':
				ircsendpass = xstrdup(optarg);
				clear_argv(argv[optind - 1]);
				break;
			case 'h':
				hexdump = 1;
				break;
			case 'u':
				username = xstrdup(optarg);
				break;
			case 'm':
				map_file = xstrdup(optarg);
				break;
			case 'L':
				conn_limit = atoi(optarg);
				break;
			case 'p':
				pid_file = xstrdup(optarg);
				break;
			case 'H':
				hint_optional = 1;
				break;
			default:
				return 1;
		}
	}

	if (hexdump)
		verbose = 1;

	if (verbose)
		detach = 0;
	
	if (detach)
		verbose = 0;

	if (argc - optind < 2) {
		usage(argv[0]);
		exit(1);
	}

	if (username && !(pw = getpwnam(username))) {
		fprintf(stderr, "%s: unknown user %s\n", argv[0], username);
		exit(1);
	}
  
	if (map_file)
		map_read();
  
	local_port = atoi(argv[optind++]);
	remote_host = argv[optind++];
	remote_port = (argc == optind) ? local_port : atoi(argv[optind]);

	debug("resolving %s\n", remote_host);

	if (!(sa = resolve_host(remote_host, remote_hint)) && !force) {
		fprintf(stderr, "%s: unable to resolve host %s\n", argv[0], remote_host);
		exit(1);
	}

	free(sa);
	sa = NULL;

	if (bind_host) {
		debug("resolving %s\n", bind_host);

		if (!(sa = resolve_host(bind_host, local_hint))) {
			fprintf(stderr, "%s: unable to resolve host %s\n", argv[0], remote_host);
			exit(1);
		}
	}
 
	debug("local: %s,%d; ", (bind_host) ? bind_host : "default", local_port);
	debug("remote: %s,%d; ", remote_host, remote_port);

	if (map_file)
		debug("source: mapped\n");
	else
		debug("source: %s\n", (source_host) ? source_host : "default");

	if (local_hint == AF_INET) {
		lsock = socket(PF_INET, SOCK_STREAM, 0);

		memset(&laddr, 0, (sa_len = sizeof(laddr)));
		laddr.sin_family = AF_INET;
		laddr.sin_port = htons(local_port);
		
		if (sa) {
			memcpy(&laddr.sin_addr, &((struct sockaddr_in*) sa)->sin_addr, sizeof(struct in_addr));
			free(sa);
		}
		
		sa = (struct sockaddr*) &laddr;
	} else {
		lsock = socket(PF_INET6, SOCK_STREAM, 0);
		
		memset(&laddr6, 0, (sa_len = sizeof(laddr6)));
		laddr6.sin6_family = AF_INET6;
		laddr6.sin6_port = htons(local_port);
		
		if (sa) {
			memcpy(&laddr6.sin6_addr, &((struct sockaddr_in6*) sa)->sin6_addr, sizeof(struct in6_addr));
			free(sa);
		}

		sa = (struct sockaddr*) &laddr6;
	}

	if (setsockopt(lsock, SOL_SOCKET, SO_REUSEADDR, &jeden, sizeof(jeden)) == -1) {
		perror("setsockopt");
		exit(1);
	}
  
	if (bind(lsock, sa, sa_len)) {
		perror("bind");
		exit(1);
	}    
  
	if (listen(lsock, 100)) {
		perror("listen");
		exit(1);
	}

	if (detach) {
		int i, ret;

		signal(SIGHUP, sighup);
		
		for (i = 0; i < 3; i++)
			close(i);

		ret = fork();
		
		if (ret == -1) {
			perror("fork");
			exit(1);
		}

		if (ret)
			exit(0);
	}

	if (pid_file) {
		FILE *f = fopen(pid_file, "w");

		if (!f)
			debug("warning: cannot write to pidfile (%s)\n", strerror(errno));
		else {
			fprintf(f, "%d", getpid());
			fclose(f);
		}
	}

	if (username && ((setgid(pw->pw_gid) == -1) || (setuid(pw->pw_uid) == -1))) {
		perror("setuid/setgid");
		exit(1);
	}

	setsid();
	signal(SIGCHLD, sigchld);
	signal(SIGTERM, sigterm);
	signal(SIGINT, sigterm);
	signal(SIGHUP, sighup);
    
	for (;;) {  
		int ret;
		fd_set rds;

		FD_ZERO(&rds);
		FD_SET(lsock, &rds);

		if (select(lsock + 1, &rds, NULL, NULL, NULL) == -1) {
			if (errno == EINTR)
				continue;

			perror("select");
			break;
		}

		if ((csock = accept(lsock, (struct sockaddr*) &caddr, &caddrlen)) == -1) {
			perror("accept");
			break;
		}

		inet_ntop(caddr.sin_family, (caddr.sin_family == AF_INET) ?
			&caddr.sin_addr :
			(void*) &(((struct sockaddr_in6*)&caddr)->sin6_addr),
			remote, sizeof(remote));

		debug("<%d> connection from %s,%d", csock, remote, ntohs(caddr.sin_port));

		if (conn_limit && (conn_count >= conn_limit)) {
			debug(" -- rejected due to limit.\n");
			shutdown(csock, 2);
			close(csock);
			continue;
		}
		
		if (conn_limit) {
			conn_count++;
			debug(" (no. %d)", conn_count);
		}
		
		fflush(stdout);
    
		if ((ret = fork()) == -1) {
			debug(" -- fork() failed.\n");
			shutdown(csock, 2);
			close(csock);
			continue;
		}
    
		if (!ret) {
			signal(SIGHUP, SIG_IGN);
			close(lsock);
			debug("\n");
			make_tunnel(csock, remote);
			debug("<%d> connection closed\n", csock);
			exit(0);
		} 

		close(csock);
    
		if (one) {
			shutdown(lsock, 2);
			close(lsock);
			exit(0);
		}

	}

	close(lsock);
  
	exit(1);
}
Example #26
0
void outwnd_print(char *id, char *tmp)
{
	char *sptr;
	char *dptr;
	int i, nrows, ccol;
	outwnd_filter_struct *temp;

	if(gr_screen.mode == GR_DIRECT3D){
		return;
	}

	if (!outwnd_inited)
		return;

	if ( Outwnd_no_filter_file == 1 )	{
		Outwnd_no_filter_file = 2;

		outwnd_print( "general", "==========================================================================\n" );
		outwnd_print( "general", "DEBUG SPEW: No debug_filter.cfg found, so only general, error, and warning\n" );
		outwnd_print( "general", "categories can be shown and no debug_filter.cfg info will be saved.\n" );
		outwnd_print( "general", "==========================================================================\n" );
	}

	if (!id)
		id = "General";

	for (i=0; i<outwnd_filter_count; i++)
		if (!stricmp(id, outwnd_filter[i]->name))
			break;


	if (i == outwnd_filter_count)  // new id found that's not yet in filter list
	{
		// Only create new filters if there was a filter file
		if ( Outwnd_no_filter_file )	{
			return;
		}

		if (outwnd_filter_count >= MAX_FILTERS) {
			Assert(outwnd_filter_count == MAX_FILTERS);  // how did it get over the max?  Very bad..
			outwnd_printf("General", "Outwnd filter limit reached.  Recycling \"%s\" to add \"%s\"",
				outwnd_filter[MAX_FILTERS - 1]->name, id);

			i--;  // overwrite the last element (oldest used filter in the list)
		}

		Assert(strlen(id) < FILTER_NAME_LENGTH);
		outwnd_filter[i] = &real_outwnd_filter[i];  // note: this assumes the list doesn't have gaps (from deleting an element for example)
		strcpy(outwnd_filter[i]->name, id);
		outwnd_filter[i]->state = 1;
		outwnd_filter_count = i + 1;
		save_filter_info();
	}

	// sort the filters from most recently used to oldest, so oldest ones will get recycled first
	temp = outwnd_filter[i];
	while (i--)
		outwnd_filter[i + 1] = outwnd_filter[i];

	i++;
	outwnd_filter[i] = temp;

	if (!outwnd_filter[i]->state)
		return;

	if (mprintf_last_line == -1 )	{
		for (i=0; i<SCROLL_BUFFER_SIZE;i++)	{
			outtext[i][0] = 0;
		}

		mprintf_last_line = 0;
	}

	// printf out to the monochrome screen first
	if ( mono_driver != ((HANDLE)-1) ) {
		DWORD   cbReturned;

		DeviceIoControl (mono_driver, (DWORD)IOCTL_MONO_PRINT, tmp, strlen(tmp), NULL, 0, &cbReturned, 0 );
	} else {
		mono_print(tmp, strlen(tmp) );
	}

	sptr = tmp;
	ccol = strlen(outtext[mprintf_last_line] );
	dptr = &outtext[mprintf_last_line][ccol];
	nrows = 0;

#ifndef NDEBUG

	if ( Log_debug_output_to_file ) {
		if ( Log_fp != NULL ) {
			fputs(tmp, Log_fp);	
			fflush(Log_fp);
		}
	}

#endif

	while(*sptr) {
		if ( (*sptr == '\n') || (ccol >= MAX_LINE_WIDTH-1 ) )	{
			nrows++;
			mprintf_last_line++;
			if (mprintf_last_line >= SCROLL_BUFFER_SIZE )
				mprintf_last_line = 0;
			ccol = 0;
			if ( *sptr != '\n' )	{
				outtext[mprintf_last_line][ccol]	= *sptr;
				ccol++;
			}
			outtext[mprintf_last_line][ccol] = '\0';
			dptr = &outtext[mprintf_last_line][ccol];
		} else {
			*dptr++ = *sptr;
			*dptr = '\0';
			ccol++;
		}
		sptr++;
	} 

	if(gr_screen.mode == GR_DIRECT3D){
		return;
	}
//	if ( D3D_enabled )	{
//		return;		// Direct3D seems to hang sometimes printing to window
//	}

	if ( outwnd_disabled ){
		return;
	}

	if ( !OutputActive )	{
		int oldpos = GetScrollPos( hOutputWnd, SB_VERT );
		if ( oldpos != max_scroll_pos )	{
			SCROLLINFO si;
			si.cbSize = sizeof(SCROLLINFO);
			si.fMask = SIF_POS;
			si.nPos = max_scroll_pos;
			SetScrollInfo(hOutputWnd, SB_VERT, &si, 1 );
			InvalidateRect(hOutputWnd,NULL,0);
			UpdateWindow(hOutputWnd);
		} else {
			if ( nrows )	{
				RECT client;
				ScrollWindow(hOutputWnd,0,-nTextHeight*nrows,NULL,NULL);
				GetClientRect(hOutputWnd, &client);
				client.top = client.bottom - nTextHeight*(nrows+1);
				InvalidateRect(hOutputWnd,&client,0);

				UpdateWindow(hOutputWnd);
			} else {
				Outwnd_changed++;
			}
		}
	}
}
void process_input (void) {
	int bufferSize = 1024;

  	short buffer[BUFLEN];
	int l, i, level;
 
	//read a block of audio samples with proper error checking
  	if ((l = read (fd_in, buffer, sizeof (buffer))) == -1) {
      		perror ("Audio read");
      		exit (-1);		/* Or return an error code */
    	}

	//we are using mono 16bit. Stereo needs to be interleaved, more difficult
  	l = l / 2;

	//checking levels stuff
	level = 0;
  	for (i = 0; i < l; i++) {
       		int v = buffer[i];

      		if (v < 0)
			v = -v;		/* abs */

      		if (v > level)
			level = v;
    	}
	
  	level = (level + 1) / 1024;
	
	//save to file
	int index;
	int charBuffIndex = 0;
	char temp[BUFLEN * 2];
	for(index = 0; index < BUFLEN * 2; index += 2){
		//fprintf(fp, "%i\n", buffer[charBuffIndex]);
		short tempshort = buffer[charBuffIndex++];
		//short tempshort = 7192;
		//add the last 8 bits
		temp[index] = tempshort & 0xFF;
		//move the first 8 bits into the last 8 bits spot
		tempshort = tempshort >> 8;
		//save the next value
		temp[index + 1] = tempshort & 0xFF;
	}


	doSend(temp);

	int iindex;
	for(iindex = 0; iindex < BUFLEN; iindex++){
		printf("%i,", buffer[iindex]);
	}
	printf("\n"); 
	//exit(0);
	//end save to file
	

	//linear scale, real world(dBD) is log
  	for (i = 0; i < level; i++)
    		printf ("*");
  	for (i = level; i < 32; i++)
    		printf (".");
  	printf ("\r");
  	fflush (stdout);
}
Example #28
0
/*! \brief
 * <pre>
 * Purpose
 * =======
 *    ilu_zdrop_row() - Drop some small rows from the previous
 *    supernode (L-part only).
 * </pre>
 */
int ilu_zdrop_row(
        superlu_options_t *options, /* options */
        int    first,       /* index of the first column in the supernode */
        int    last,        /* index of the last column in the supernode */
        double drop_tol,    /* dropping parameter */
        int    quota,       /* maximum nonzero entries allowed */
        int    *nnzLj,      /* in/out number of nonzeros in L(:, 1:last) */
        double *fill_tol,   /* in/out - on exit, fill_tol=-num_zero_pivots,
                             * does not change if options->ILU_MILU != SMILU1 */
        GlobalLU_t *Glu,    /* modified */
        double dwork[],   /* working space
                             * the length of dwork[] should be no less than
                             * the number of rows in the supernode */
        double dwork2[], /* working space with the same size as dwork[],
                             * used only by the second dropping rule */
        int    lastc        /* if lastc == 0, there is nothing after the
                             * working supernode [first:last];
                             * if lastc == 1, there is one more column after
                             * the working supernode. */ )
{
    register int i, j, k, m1;
    register int nzlc; /* number of nonzeros in column last+1 */
    register int xlusup_first, xlsub_first;
    int m, n; /* m x n is the size of the supernode */
    int r = 0; /* number of dropped rows */
    register double *temp;
    register doublecomplex *lusup = Glu->lusup;
    register int *lsub = Glu->lsub;
    register int *xlsub = Glu->xlsub;
    register int *xlusup = Glu->xlusup;
    register double d_max = 0.0, d_min = 1.0;
    int    drop_rule = options->ILU_DropRule;
    milu_t milu = options->ILU_MILU;
    norm_t nrm = options->ILU_Norm;
    doublecomplex zero = {0.0, 0.0};
    doublecomplex one = {1.0, 0.0};
    doublecomplex none = {-1.0, 0.0};
    int i_1 = 1;
    int inc_diag; /* inc_diag = m + 1 */
    int nzp = 0;  /* number of zero pivots */
    double alpha = pow((double)(Glu->n), -1.0 / options->ILU_MILU_Dim);

    xlusup_first = xlusup[first];
    xlsub_first = xlsub[first];
    m = xlusup[first + 1] - xlusup_first;
    n = last - first + 1;
    m1 = m - 1;
    inc_diag = m + 1;
    nzlc = lastc ? (xlusup[last + 2] - xlusup[last + 1]) : 0;
    temp = dwork - n;

    /* Quick return if nothing to do. */
    if (m == 0 || m == n || drop_rule == NODROP)
    {
        *nnzLj += m * n;
        return 0;
    }

    /* basic dropping: ILU(tau) */
    for (i = n; i <= m1; )
    {
        /* the average abs value of ith row */
        switch (nrm)
        {
            case ONE_NORM:
                temp[i] = dzasum_(&n, &lusup[xlusup_first + i], &m) / (double)n;
                break;
            case TWO_NORM:
                temp[i] = dznrm2_(&n, &lusup[xlusup_first + i], &m)
                    / sqrt((double)n);
                break;
            case INF_NORM:
            default:
                k = izamax_(&n, &lusup[xlusup_first + i], &m) - 1;
                temp[i] = z_abs1(&lusup[xlusup_first + i + m * k]);
                break;
        }

        /* drop small entries due to drop_tol */
        if (drop_rule & DROP_BASIC && temp[i] < drop_tol)
        {
            r++;
            /* drop the current row and move the last undropped row here */
            if (r > 1) /* add to last row */
            {
                /* accumulate the sum (for MILU) */
                switch (milu)
                {
                    case SMILU_1:
                    case SMILU_2:
                        zaxpy_(&n, &one, &lusup[xlusup_first + i], &m,
                                &lusup[xlusup_first + m - 1], &m);
                        break;
                    case SMILU_3:
                        for (j = 0; j < n; j++)
                            lusup[xlusup_first + (m - 1) + j * m].r +=
                                    z_abs1(&lusup[xlusup_first + i + j * m]);
                        break;
                    case SILU:
                    default:
                        break;
                }
                zcopy_(&n, &lusup[xlusup_first + m1], &m,
                       &lusup[xlusup_first + i], &m);
            } /* if (r > 1) */
            else /* move to last row */
            {
                zswap_(&n, &lusup[xlusup_first + m1], &m,
                        &lusup[xlusup_first + i], &m);
                if (milu == SMILU_3)
                    for (j = 0; j < n; j++) {
                        lusup[xlusup_first + m1 + j * m].r =
                                z_abs1(&lusup[xlusup_first + m1 + j * m]);
                        lusup[xlusup_first + m1 + j * m].i = 0.0;
                    }
            }
            lsub[xlsub_first + i] = lsub[xlsub_first + m1];
            m1--;
            continue;
        } /* if dropping */
        else
        {
            if (temp[i] > d_max) d_max = temp[i];
            if (temp[i] < d_min) d_min = temp[i];
        }
        i++;
    } /* for */

    /* Secondary dropping: drop more rows according to the quota. */
    quota = ceil((double)quota / (double)n);
    if (drop_rule & DROP_SECONDARY && m - r > quota)
    {
        register double tol = d_max;

        /* Calculate the second dropping tolerance */
        if (quota > n)
        {
            if (drop_rule & DROP_INTERP) /* by interpolation */
            {
                d_max = 1.0 / d_max; d_min = 1.0 / d_min;
                tol = 1.0 / (d_max + (d_min - d_max) * quota / (m - n - r));
            }
            else /* by quick select */
            {
                int len = m1 - n + 1;
                dcopy_(&len, dwork, &i_1, dwork2, &i_1);
                tol = dqselect(len, dwork2, quota - n);
#if 0
                register int *itemp = iwork - n;
                A = temp;
                for (i = n; i <= m1; i++) itemp[i] = i;
                qsort(iwork, m1 - n + 1, sizeof(int), _compare_);
                tol = temp[itemp[quota]];
#endif
            }
        }

        for (i = n; i <= m1; )
        {
            if (temp[i] <= tol)
            {
                register int j;
                r++;
                /* drop the current row and move the last undropped row here */
                if (r > 1) /* add to last row */
                {
                    /* accumulate the sum (for MILU) */
                    switch (milu)
                    {
                        case SMILU_1:
                        case SMILU_2:
                            zaxpy_(&n, &one, &lusup[xlusup_first + i], &m,
                                    &lusup[xlusup_first + m - 1], &m);
                            break;
                        case SMILU_3:
                            for (j = 0; j < n; j++)
                                lusup[xlusup_first + (m - 1) + j * m].r +=
                                  z_abs1(&lusup[xlusup_first + i + j * m]);
                            break;
                        case SILU:
                        default:
                            break;
                    }
                    zcopy_(&n, &lusup[xlusup_first + m1], &m,
                            &lusup[xlusup_first + i], &m);
                } /* if (r > 1) */
                else /* move to last row */
                {
                    zswap_(&n, &lusup[xlusup_first + m1], &m,
                            &lusup[xlusup_first + i], &m);
                    if (milu == SMILU_3)
                        for (j = 0; j < n; j++) {
                            lusup[xlusup_first + m1 + j * m].r =
                                    z_abs1(&lusup[xlusup_first + m1 + j * m]);
                            lusup[xlusup_first + m1 + j * m].i = 0.0;
                        }
                }
                lsub[xlsub_first + i] = lsub[xlsub_first + m1];
                m1--;
                temp[i] = temp[m1];

                continue;
            }
            i++;

        } /* for */

    } /* if secondary dropping */

    for (i = n; i < m; i++) temp[i] = 0.0;

    if (r == 0)
    {
        *nnzLj += m * n;
        return 0;
    }

    /* add dropped entries to the diagnal */
    if (milu != SILU)
    {
        register int j;
        doublecomplex t;
        double omega;
        for (j = 0; j < n; j++)
        {
            t = lusup[xlusup_first + (m - 1) + j * m];
            if (t.r == 0.0 && t.i == 0.0) continue;
            omega = SUPERLU_MIN(2.0 * (1.0 - alpha) / z_abs1(&t), 1.0);
            zd_mult(&t, &t, omega);

            switch (milu)
            {
                case SMILU_1:
                    if ( !(z_eq(&t, &none)) ) {
                        z_add(&t, &t, &one);
                        zz_mult(&lusup[xlusup_first + j * inc_diag],
                                          &lusup[xlusup_first + j * inc_diag],
                                          &t);
                    }
                    else
                    {
                        zd_mult(
                                &lusup[xlusup_first + j * inc_diag],
                                &lusup[xlusup_first + j * inc_diag],
                                *fill_tol);
#ifdef DEBUG
                        printf("[1] ZERO PIVOT: FILL col %d.\n", first + j);
                        fflush(stdout);
#endif
                        nzp++;
                    }
                    break;
                case SMILU_2:
                    zd_mult(&lusup[xlusup_first + j * inc_diag],
                                          &lusup[xlusup_first + j * inc_diag],
                                          1.0 + z_abs1(&t));
                    break;
                case SMILU_3:
                    z_add(&t, &t, &one);
                    zz_mult(&lusup[xlusup_first + j * inc_diag],
                                      &lusup[xlusup_first + j * inc_diag],
                                      &t);
                    break;
                case SILU:
                default:
                    break;
            }
        }
        if (nzp > 0) *fill_tol = -nzp;
    }

    /* Remove dropped entries from the memory and fix the pointers. */
    m1 = m - r;
    for (j = 1; j < n; j++)
    {
        register int tmp1, tmp2;
        tmp1 = xlusup_first + j * m1;
        tmp2 = xlusup_first + j * m;
        for (i = 0; i < m1; i++)
            lusup[i + tmp1] = lusup[i + tmp2];
    }
    for (i = 0; i < nzlc; i++)
        lusup[xlusup_first + i + n * m1] = lusup[xlusup_first + i + n * m];
    for (i = 0; i < nzlc; i++)
        lsub[xlsub[last + 1] - r + i] = lsub[xlsub[last + 1] + i];
    for (i = first + 1; i <= last + 1; i++)
    {
        xlusup[i] -= r * (i - first);
        xlsub[i] -= r;
    }
    if (lastc)
    {
        xlusup[last + 2] -= r * n;
        xlsub[last + 2] -= r;
    }

    *nnzLj += (m - r) * n;
    return r;
}
bool
HostFileHandle::flush()
{
   decaf_check(mHandle);
   return !!fflush(mHandle);
}
Example #30
0
int main(int argc, char *argv[])
{
    int i;
    int j;
    char* buffer;
    int use_stdout = FALSE;
    int skip_invalid = FALSE;
    int num_entries = 0;

    int verbose = FALSE;
    char* file_name_in = 0;
    char* file_name_out = 0;
    char separator_sign = ' ';
    char* parse_string = "xyz";

    int64_t global_offset_x = 0;
    int64_t global_offset_y = 0;
    int check = FALSE;
    double scale_x;
    double scale_y;

    LASReaderH reader = NULL;
    LASHeaderH header = NULL;
    LASPointH p = NULL;
    FILE* file_out;
    int len;

    unsigned int index = 0;
    if (argc == 1) {
        usage();
        exit(0);
    }

    for (i = 1; i < argc; i++)
    {
        if (    strcmp(argv[i],"-h") == 0 ||
                strcmp(argv[i],"-help") == 0 ||
                strcmp(argv[i],"--help") == 0
           )
        {
            usage();
            exit(0);
        }
        else if (   strcmp(argv[i],"-v") == 0 ||
                strcmp(argv[i],"--verbose") == 0
                )
        {
            verbose = TRUE;
        }
        else if (   strcmp(argv[i],"-s") == 0 ||
                strcmp(argv[i],"--skip_invalid") == 0
                )
        {
            skip_invalid = TRUE;
        }
        else if (   strcmp(argv[i], "--parse") == 0 ||
                    strcmp(argv[i], "-parse") == 0
                )
        {
            i++;
            parse_string = argv[i];
        }
        else if (   strcmp(argv[i], "--moffset") == 0 ||
                    strcmp(argv[i], "-moffset") == 0
                )
        {
            i++;
            buffer = strtok (argv[i], ",");
            j = 0;
            while (buffer) {
                if (j == 0) {
                    global_offset_x = S64(buffer);
                }
                else if (j == 1) {
                    global_offset_y = S64(buffer);
                }
                j++;
                buffer = strtok (NULL, ",");
                while (buffer && *buffer == '\040')
                    buffer++;
            }
            if (j != 2){
                fprintf(stderr, "Only two int64_t are required in moffset option!\n");
                exit(1);
            }

        }
        else if (   strcmp(argv[i], "--check") == 0 ||
                    strcmp(argv[i], "-check") == 0
                )
        {
            i++;
            check = TRUE;
            buffer = strtok (argv[i], ",");
            j = 0;
            while (buffer) {
                if (j == 0) {
                    sscanf(buffer, "%lf", &scale_x);
                }
                else if (j == 1) {
                    sscanf(buffer, "%lf", &scale_y);
                }
                j++;
                buffer = strtok (NULL, ",");
                while (buffer && *buffer == '\040')
                    buffer++;
            }
            if (j != 2){
                fprintf(stderr, "Only two doubles are required in moffset option!\n");
                exit(1);
            }
        }
        else if (   strcmp(argv[i], "--stdout") == 0
                )
        {
            use_stdout = TRUE;
        }
        else if (   strcmp(argv[i],"--input") == 0  ||
                strcmp(argv[i],"-input") == 0   ||
                strcmp(argv[i],"-i") == 0       ||
                strcmp(argv[i],"-in") == 0
                )
        {
            i++;
            file_name_in = argv[i];
        }
        else if (   strcmp(argv[i],"--output") == 0  ||
                    strcmp(argv[i],"--out") == 0     ||
                    strcmp(argv[i],"-out") == 0     ||
                    strcmp(argv[i],"-o") == 0
                )
        {
            i++;
            file_name_out = argv[i];
        }
        else if (file_name_in == 0 && file_name_out == 0)
        {
            file_name_in = argv[i];
        }
        else if (file_name_in && file_name_out == 0)
        {
            file_name_out = argv[i];
        }
        else
        {
            fprintf(stderr, "ERROR: unknown argument '%s'\n",argv[i]);
            usage();
            exit(1);
        }
    } /* end looping through argc/argv */
    num_entries = strlen(parse_string);

    if (use_stdout == TRUE && file_name_out){
      LASError_Print("If an output file is specified, --stdout must not be used!");
      exit(1);
    }

    reader = LASReader_Create(file_name_in);
    if (!reader) {
        LASError_Print("Unable to read file");
        exit(1);
    }

    header = LASReader_GetHeader(reader);
    if (!header) {
        LASError_Print("Unable to fetch header for file");
        exit(1);
    }

    if (use_stdout)
    {
        file_out = stdout;
    }
    else
    {
        if (file_name_out == NULL)
        {
            if (file_name_in == NULL)
            {
                LASError_Print("No input filename was specified");
                usage();
                exit(1);
            }

            len = (int)strlen(file_name_in);
            file_name_out = LASCopyString(file_name_in);
            if (file_name_out[len-3] == '.' && file_name_out[len-2] == 'g' && file_name_out[len-1] == 'z')
            {
                len = len - 4;
            }
            while (len > 0 && file_name_out[len] != '.')
            {
                len--;
            }
            file_name_out[len] = '\0';
        }
        file_out = fopen(file_name_out, "wb");
    }

    if (file_out == 0)
    {
        LASError_Print("Could not open file for write");
        usage();
        exit(1);
    }

    if (verbose)
    {
        print_header(stderr, header, file_name_in);
    }

    // Compute factors to add to X and Y and check sanity of generated codes
    double file_scale_x = LASHeader_GetScaleX(header);
    double file_scale_y = LASHeader_GetScaleY(header);

    if (check)
    {
        // Check specified scales are like in the LAS file
        if (fabs(scale_x - file_scale_x) > TOLERANCE){
        fprintf(stderr, "ERROR: x scale in input file (%lf) does not match specified x scale (%lf)\n",file_scale_x, scale_x);
            exit(1);
        }
        if (fabs(scale_y - file_scale_y) > TOLERANCE){
            fprintf(stderr, "ERROR: y scale in input file (%lf) does not match specified y scale (%lf)\n",file_scale_y, scale_y);
            exit(1);
        }
        /* Check that the extent of the file (taking into account the global offset)
         * is within 0,2^31 */
        double check_min_x = 1.0 + LASHeader_GetMinX(header) - (((double) global_offset_x) * scale_x);
        if (check_min_x < TOLERANCE) {
            fprintf(stderr, "ERROR: Specied X global offset is too large. (MinX - (GlobalX*ScaleX)) < 0\n");
            exit(1);
        }
        double check_min_y = 1.0 + LASHeader_GetMinY(header) - (((double) global_offset_y) * scale_y);
        if (check_min_y < TOLERANCE) {
            fprintf(stderr, "ERROR: Specied Y global offset is too large. (MinY - (GlobalY*ScaleY)) < 0\n");
            exit(1);
        }
        double check_max_x = LASHeader_GetMaxX(header) - (((double) global_offset_x) * scale_x);
        if (check_max_x > (MAX_INT_31 * scale_x)) {
            fprintf(stderr, "ERROR: Specied X global offset is too small. (MaxX - (GlobalX*ScaleX)) > (2^31)*ScaleX\n");
            exit(1);
        }
        double check_max_y = LASHeader_GetMaxY(header) - (((double) global_offset_y) * scale_y);
        if (check_max_y > (MAX_INT_31 * scale_y)) {
            fprintf(stderr, "ERROR: Specied Y global offset is too small. (MaxY - (GlobalY*ScaleY)) > (2^31)*ScaleY\n");
            exit(1);
        }
    }


    /*Write Postgres header*/
    struct postHeader pgHeader;
    pgHeader.s = "PGCOPY\n\377\r\n\0";
    int i1T = 0, i2T = 0;
    pgHeader.i1 = htonl(i1T);
    pgHeader.i2 = htonl(i2T);
    fwrite(pgHeader.s, 11, 1, file_out);
    fwrite(&pgHeader.i1, sizeof(uint32_t), 1, file_out);
    fwrite(&pgHeader.i2, sizeof(uint32_t), 1, file_out);

    /* declaration for morton*/
    uint32_t rawx = 0;
    uint32_t rawy = 0;
    uint64_t mortonkey = 0;

    /* scaled offsets to add for the morton encoding */
    int64_t factorX =  ((int64_t) (LASHeader_GetOffsetX(header) / file_scale_x)) - global_offset_x;
    int64_t factorY =  ((int64_t) (LASHeader_GetOffsetY(header) / file_scale_y)) - global_offset_y;

    p = LASReader_GetNextPoint(reader);
    while (p)
    {
        if (skip_invalid && !LASPoint_IsValid(p)) {
            if (verbose) {
                LASError_Print("Skipping writing invalid point...");
            }
            p = LASReader_GetNextPoint(reader);
            index -=1;
            continue;
        }
        struct postRow pgRow;
        uint32_t size;
        uint16_t hT = num_entries;
        pgRow.h = htons(hT);
        fwrite(& pgRow.h, 2, 1, file_out);
        size = sizeof(double);
        pgRow.vardSize = htonl(size);
        size = sizeof(uint32_t);
        pgRow.varSize = htonl(size);

        i = 0;
        for (;;)
        {
            LASColorH color = LASPoint_GetColor(p);
            double vard;
            int var;
            unsigned long long int vardL, varL;

            switch (parse_string[i])
               {
                    /* // the morton code on xy */
                case 'k':
                    rawx = (uint32_t) (((int64_t) LASPoint_GetRawX(p)) + factorX);
                    rawy = (uint32_t) (((int64_t) LASPoint_GetRawY(p)) + factorY);
                    mortonkey = EncodeMorton2D(rawx,rawy);
                    varL = htobe64(mortonkey);
                    fwrite(&pgRow.vardSize, sizeof(uint32_t), 1, file_out);
                    fwrite(&varL, sizeof(uint64_t), 1, file_out);
                    break;
                    /* // the x coordinate */
                case 'x':
                    vard = LASPoint_GetX(p);
                    fwrite(&pgRow.vardSize, sizeof(uint32_t), 1, file_out);
                    vardL = bigEndian_double(vard);
                    fwrite(&vardL, sizeof(double), 1, file_out);
                    break;
                    /* // the y coordinate */
                case 'y':
                    vard = LASPoint_GetY(p);
                    fwrite(&pgRow.vardSize, sizeof(uint32_t), 1, file_out);
                    vardL = bigEndian_double(vard);
                    fwrite(&vardL, sizeof(double), 1, file_out);
                    break;
                    /* // the z coordinate */
                case 'z':
                    vard = LASPoint_GetZ(p);
                    fwrite(&pgRow.vardSize, sizeof(uint32_t), 1, file_out);
                    vardL = bigEndian_double(vard);
                    fwrite(&vardL, sizeof(double), 1, file_out);
                    break;
                    /* // the gps-time */
                case 't':
                    vard = LASPoint_GetTime(p);
                    fwrite(&pgRow.vardSize, sizeof(uint32_t), 1, file_out);
                    vardL = bigEndian_double(vard);
                    fwrite(&vardL, sizeof(double), 1, file_out);
                    break;
                    /* // the intensity */
                case 'i':
                    var = LASPoint_GetIntensity(p);
                    fwrite(&pgRow.varSize, sizeof(uint32_t), 1, file_out);
                    varL = htonl(var);
                    fwrite(&varL, sizeof(uint32_t), 1, file_out);
                    break;
                    /* the scan angle */
                case 'a':
                    var = LASPoint_GetScanAngleRank(p);
                    fwrite(&pgRow.varSize, sizeof(uint32_t), 1, file_out);
                    varL = htonl(var);
                    fwrite(&varL, sizeof(uint32_t), 1, file_out);
                    break;
                    /* the number of the return */
                case 'r':
                    var = LASPoint_GetReturnNumber(p);
                    fwrite(&pgRow.varSize, sizeof(uint32_t), 1, file_out);
                    varL = htonl(var);
                    fwrite(&varL, sizeof(uint32_t), 1, file_out);
                    break;
                    /* the classification */
                case 'c':
                    var = LASPoint_GetClassification(p);
                    fwrite(&pgRow.varSize, sizeof(uint32_t), 1, file_out);
                    varL = htonl(var);
                    fwrite(&varL, sizeof(uint32_t), 1, file_out);
                    break;
                    /* the user data */
                case 'u':
                    var = LASPoint_GetUserData(p);
                    fwrite(&pgRow.varSize, sizeof(uint32_t), 1, file_out);
                    varL = htonl(var);
                    fwrite(&varL, sizeof(uint32_t), 1, file_out);
                    break;
                    /* the number of returns of given pulse */
                case 'n':
                    var = LASPoint_GetNumberOfReturns(p);
                    fwrite(&pgRow.varSize, sizeof(uint32_t), 1, file_out);
                    varL = htonl(var);
                    fwrite(&varL, sizeof(uint32_t), 1, file_out);
                    break;
                    /* the red channel color */
                case 'R':
                    var = LASColor_GetRed(color);
                    fwrite(&pgRow.varSize, sizeof(uint32_t), 1, file_out);
                    varL = htonl(var);
                    fwrite(&varL, sizeof(uint32_t), 1, file_out);
                    break;
                    /* the green channel color */
                case 'G':
                    var = LASColor_GetGreen(color);
                    fwrite(&pgRow.varSize, sizeof(uint32_t), 1, file_out);
                    varL = htonl(var);
                    fwrite(&varL, sizeof(uint32_t), 1, file_out);
                    break;
                    /* the blue channel color */
                case 'B':
                    var = LASColor_GetBlue(color);
                    fwrite(&pgRow.varSize, sizeof(uint32_t), 1, file_out);
                    varL = htonl(var);
                    fwrite(&varL, sizeof(uint32_t), 1, file_out);
                    break;
                case 'M':
                    var = index;
                    fwrite(&pgRow.varSize, sizeof(uint32_t), 1, file_out);
                    varL = htonl(var);
                    fwrite(&varL, sizeof(uint32_t), 1, file_out);
                    break;
                case 'p':
                    var = LASPoint_GetPointSourceId(p);
                    fwrite(&pgRow.varSize, sizeof(uint32_t), 1, file_out);
                    varL = htonl(var);
                    fwrite(&varL, sizeof(uint32_t), 1, file_out);
                    break;
                    /* the edge of flight line flag */
                case 'e':
                    var = LASPoint_GetFlightLineEdge(p);
                    fwrite(&pgRow.varSize, sizeof(uint32_t), 1, file_out);
                    varL = htonl(var);
                    fwrite(&varL, sizeof(uint32_t), 1, file_out);
                    break;
                    /* the direction of scan flag */
                case 'd':
                    var = LASPoint_GetScanDirection(p);
                    fwrite(&pgRow.varSize, sizeof(uint32_t), 1, file_out);
                    varL = htonl(var);
                    fwrite(&varL, sizeof(uint32_t), 1, file_out);
                    break;
            }
            i++;
            if (!parse_string[i])
            {
                break;
            }
            LASColor_Destroy(color);
        }
        p = LASReader_GetNextPoint(reader);
        index +=1;
    }
    short endT = -1;
    short end = htons(endT);
    fwrite(&end, sizeof(end), 1, file_out);

    fflush(file_out);
    fclose(file_out);

    LASReader_Destroy(reader);
    LASHeader_Destroy(header);
    return 0;
}