Exemplo n.º 1
0
/*
 * The buffers used for file data are allocated as a single big
 * malloc, and then each thread and operation takes a piece and uses
 * that for file data.  This lets us do a large shm or bigpages alloc
 * and without trying to find a special place in each thread to map the
 * buffers to
 */
int setup_shared_mem(int num_threads, int num_files, int depth,
		     int reclen, int max_io_submit)
{
	char *p = NULL;
	size_t total_ram;

	padded_reclen = (reclen + page_size_mask) / (page_size_mask + 1);
	padded_reclen = padded_reclen * (page_size_mask + 1);
	total_ram = num_files * depth * padded_reclen + num_threads;
	if (verify)
		total_ram += padded_reclen;

	/* for aligning buffer after the allocation */
	total_ram += page_size_mask;

	if (use_shm == USE_MALLOC) {
		p = malloc(total_ram);
	} else if (use_shm == USE_SHM) {
		shm_id = shmget(IPC_PRIVATE, total_ram, IPC_CREAT | 0700);
		if (shm_id < 0) {
			perror("shmget");
			drop_shm();
			goto free_buffers;
		}
		p = shmat(shm_id, (char *)0x50000000, 0);
		if ((long)p == -1) {
			perror("shmat");
			goto free_buffers;
		}
		/* won't really be dropped until we shmdt */
		drop_shm();
	} else if (use_shm == USE_SHMFS) {
		char mmap_name[16];	/* /dev/shm/ + null + XXXXXX */
		int fd;

		strcpy(mmap_name, "/dev/shm/XXXXXX");
		fd = mkstemp(mmap_name);
		if (fd < 0) {
			perror("mkstemp");
			goto free_buffers;
		}
		unlink(mmap_name);
		ftruncate(fd, total_ram);
		shm_id = fd;
		p = mmap((char *)0x50000000, total_ram,
			 PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

		if (p == MAP_FAILED) {
			perror("mmap");
			goto free_buffers;
		}
	}
	if (!p) {
		fprintf(stderr, "unable to allocate buffers\n");
		goto free_buffers;
	}
	unaligned_buffer = p;
	p = (char *)((intptr_t) (p + page_size_mask) & ~page_size_mask);
	aligned_buffer = p;
	return 0;

free_buffers:
	drop_shm();
	if (unaligned_buffer)
		free(unaligned_buffer);
	return -1;
}
Exemplo n.º 2
0
/** 
  * Write udhcpd.conf
  * @ipforward : NULL if we want a simple config, otherwise include dns info etc...
  */
static int write_udhcpd_conf(struct ipforward_data *ipforward, struct mode_list_elem *data)
{
  FILE *conffile;
  char *ip, *interface;
  char *ipstart, *ipend;
  int dot = 0, i = 0, test;
  struct stat st;

  /* /tmp is often tmpfs, so we avoid writing to flash */
  conffile = fopen("/tmp/udhcpd.conf", "w");
  if(conffile == NULL)
  {
	log_debug("Error creating /etc/udhcpd.conf!\n");
	return(1);
  }

  /* generate start and end ip based on the setting */
  ip = get_network_ip();
  if(ip == NULL)
  {
	ip = strdup("192.168.2.15");
  }
  ipstart = malloc(sizeof(char)*15);
  ipend = malloc(sizeof(char)*15);
  while(i < 15)
  {
        if(dot < 3)
        {
                if(ip[i] == '.')
                        dot ++;
                ipstart[i] = ip[i];
                ipend[i] = ip[i];
        }
        else
        {
                ipstart[i] = '\0';
                ipend[i] = '\0';
                break;
        }
        i++;
  }
  strcat(ipstart,"1");
  strcat(ipend, "10");

  interface = get_interface(data);
  /* print all data in the file */
  fprintf(conffile, "start\t%s\n", ipstart);
  fprintf(conffile, "end\t%s\n", ipend);
  fprintf(conffile, "interface\t%s\n", interface);
  fprintf(conffile, "option\tsubnet\t255.255.255.0\n");
  if(ipforward != NULL)
  {
	if(!ipforward->dns1 || !ipforward->dns2)
	{
		log_debug("No dns info!");
	}
	else
		fprintf(conffile, "opt\tdns\t%s %s\n", ipforward->dns1, ipforward->dns2);
	fprintf(conffile, "opt\trouter\t%s\n", ip);
  }

  free(ipstart);
  free(ipend);
  free(ip);
  free(interface);
  fclose(conffile);
  log_debug("/etc/udhcpd.conf written.\n");

  /* check if it is a symlink, if not remove and link, create the link if missing */
  test = stat("/etc/udhcpd.conf", &st);
  /* if stat fails there is no file or link */
  if(test == -1)
	goto link;
  /* if it is not a link we remove it, else we expect the right link to be there */
  if((st.st_mode & S_IFMT) != S_IFLNK)
  {
	unlink("/etc/udhcpd.conf");
  }
  else
	goto end;

link:
  symlink("/tmp/udhcpd.conf", "/etc/udhcpd.conf");

end:

  return(0);
}
Exemplo n.º 3
0
/* Main Function */
int main(int argc, char** argv) {
	
	/* Variables definitons*/
	FILEPTR fPtrInput,fPtrOutput;
	pid_t pidtIsParent;
	char* chPtrWord;
	int iWordCount;
	int linesArray[MAXLINESIZE]; 
	int* lines = &linesArray[0];
	int i,j,totalFilesNum,totalTextFilesNum,tempLine;
	int lineOccur=0;
	CHPTR dirName;
	char chPtrFileName[LINESIZE];
	FILEPTR fPtrFile;
	pid_t pidParent = getpid();
	char filesFound[MAXLINESIZE][LINESIZE];	
	int txtFilesIndex[LINESIZE];
	int stat;
	char tempChar[LINESIZE],ch,tch;
	char printLineStr[100]; 
	int len;
	int printLineCount;
	struct sigaction act;
	int fd;
    char * myfifo = "/tmp/myfifo";
	char fifoBuffer[4096];
	
	/* Check Usage exclude print count */
	if(!myUsage(argc, argv))
		return 1;

	/* 
	 * Assignment directory name and print count 
	 * Check print count is vaild
	 */
	dirName = argv[1];
	printLineCount=atoi(argv[5]);
	if(printLineCount<=0){
		myUsage(printLineCount,argv);
		return 1;
	}
	
	act.sa_handler = setdoneflag;
	 /* set up signal handler */
	act.sa_flags = 0;

	if ((sigemptyset(&act.sa_mask) == -1) || (sigaction(SIGINT, &act, NULL) == -1)) {
		perror("Failed to set SIGINT handler");
		return 1;
	}	
	
	puts("Parent");
	printf("%-8s %s\n","PID", "FILE NAME");
	puts("==================================================================");
	/* Find and record files,directories */ 

	
	
	recDirWithFork(dirName,1,getpid());

	/* Parent will print the contents of its own file and remove it */
	if(getpid() == pidParent) {
		getFileName(chPtrFileName, dirName);
		fPtrFile = fopen(chPtrFileName, "r");
		
		/* Assign loop total founded files and directories */
		for(j=0,stat=fscanf(fPtrFile,"%s",filesFound[j]);stat!=EOF;++j,stat=fscanf(fPtrFile,"%s",filesFound[j])){}
			totalFilesNum=j;

		/* Assign loop total founded text files */
		totalTextFilesNum=0;
		for(j=0;j<totalFilesNum;++j){
			len=strlen(filesFound[j]);
				if (len > 4 && strcmp(filesFound[j] + len - 4, ".txt") == 0){
					txtFilesIndex[totalTextFilesNum]=j;
					totalTextFilesNum++;	    
			}		
		}
		/* Printing total founded text files to stdin */
		puts("Total text files found:");
		for(j=0;j<totalTextFilesNum;++j){
			strcpy(tempChar,argv[1]);
			strcat(tempChar,filesFound[txtFilesIndex[j]]);
			strcpy(filesFound[txtFilesIndex[j]],tempChar);
			printf("%s\n",filesFound[txtFilesIndex[j]]);
		}
		/* 
		 * Close filepointer and delete total founded files 
		 * and directories file 
		 */	
		fclose(fPtrFile);
		unlink(chPtrFileName);
	
		/* 
		 * Record loop for word counts and lines 
		 * to the linesOutput.txt file 
		 */
		for(j=0;j<totalTextFilesNum;++j){
			/* Creating child process */
			pidtIsParent = fork();
			/* Setting the current process' argument. */
			chPtrWord = argv[3];
			
			/* If child process*/
			if (!pidtIsParent) {
				/* Opening files */
				fPtrInput = fopen(filesFound[txtFilesIndex[j]], "r");
				fPtrOutput = fopen("fifoOutput.txt","a+");
	
				/* Checking whether the files was opened */
				if (fPtrInput == NULL) {
					fprintf(stderr, "Cannot open input file.\n");
					return 2;
				}
				if(fPtrOutput==NULL){
					fprintf(stderr, "Child process can not update the output file.\n");
					return 2;
				}

				/* Getting the number of occurrences in files*/
				iWordCount = findOccurrenceNum(fPtrInput, chPtrWord , lines);
					
				/* Printing to file the child processes information */
				fprintf(fPtrOutput,"Word: %-20s Count: #%-5d pId: %-6d ppId:%-6d \n", chPtrWord,
					iWordCount, getpid(), getppid());
							
				/* Member initilization before the loop */ 			
				tempLine=0;
				lineOccur=0;
				fprintf(fPtrOutput,"File:%s\n",filesFound[txtFilesIndex[j]]);
				/* Loop for record lines informations to the linesOutput.txt*/
				for(i=0;i<iWordCount;++i){
					if(i==0 && iWordCount!=1){
						 fprintf(fPtrOutput,"Lines are:\n");
						 tempLine=lines[0];	
						 ++lineOccur;			
					}
					else if(i==0 && iWordCount==1)
						 fprintf(fPtrOutput,"Line Number %d Number of occurrences %d\n",lines[i],lineOccur+1);
					else if(i==iWordCount-1)
						 fprintf(fPtrOutput,"Line Number %d Number of occurrences %d\n",lines[i],lineOccur+1);
					else{
						 if(tempLine==lines[i]){
							++lineOccur;
						 }	
						 else{
							fprintf(fPtrOutput,"Line Number %d Number of occurrences %d\n",lines[i-1],lineOccur);
							lineOccur=1;
							tempLine=lines[i];
						 }				
					}	
				}
				/* Safely closing the file pointers */
				fclose(fPtrInput);
				fclose(fPtrOutput);
				/* Child processes ends */
				return 0;
		
			}
			/* Waiting for the current child process */
			while (childWait(NULL ) > 0);
		}

		/* Open linesOutput.txt files */
		fPtrInput=fopen("fifoOutput.txt","r");
		/* Checking whether the file was opened */
		if(fPtrInput==NULL){
			fprintf(stderr, "Parent process can not open the fifoOutput file.\n");
			return 2;
		}	
		/* 
		 * For separate founded text files list and
		 *  lines of word in the file 
		 */
		puts("\n\n");	
		/* Make fifo */
		if (mkfifo(myfifo, 0666) < 0) {
			if (errno != EEXIST) {
				perror("mkfifo");
				exit(EXIT_FAILURE);
			}
		}
		/* Open fifo with read and write mode */	
		fd = open(myfifo, O_RDWR);		
		/* Fifo read and write loop */
		while(fgets(printLineStr,100,fPtrInput)!=NULL){
			/* Child processes are read file line by line */
			/* Write to the fifo */
			int fifoStat;
			fifoStat = fork(); 
			
			if(fifoStat<0){
				perror("Fork ");
				exit(EXIT_FAILURE);
			}
			else if(!fifoStat){
				write(fd, printLineStr, sizeof(printLineStr));
				return 0;
			}
			else{
				/* Child wait */
				while (childWait(NULL) > 0);
				fPtrOutput=fopen("linesOutput.txt","a+");
				/* Checking whether the file was opened */
				if(fPtrOutput==NULL){
					fprintf(stderr, "Parent process can not open the output file.\n");
					return 2;
				}				
				/* Parent Process read from fifo */
				/* Write to the output file */
				read(fd, fifoBuffer, 4096);	
				fprintf(fPtrOutput,"%s",fifoBuffer);
			}
		}
		/* Safely close and unlink files,pointers and fifo */
		unlink("fifoOutput.txt");
		fclose(fPtrInput);	
		fclose(fPtrOutput);
		unlink(myfifo);		
		close(fd);
		
		/* Open linesOutput.txt files */
		fPtrOutput=fopen("linesOutput.txt","r");
		/* Checking whether the file was opened */
		if(fPtrOutput==NULL){
			fprintf(stderr, "Parent process can not open the output file.\n");
			return 2;
		}
		
		
		
		/* Do-while loop print like less command in UNIX */
		do{
			/* Print lines loop*/
			for(i=1;i<=printLineCount;++i){
				if(fgets(printLineStr,100,fPtrOutput)!=NULL){
					printf("%s",printLineStr);		
				}
				/* If file is over */	
				else{
					puts("FILE IS OVER...\n");
					fclose(fPtrOutput);
					unlink("linesOutput.txt");
				
					/* Printing the parent processes information */
					printf("%s pId: %d \n", "\n\nDone parent.", getpid());
					return 0;
				}		
			}
			/* Like less command */
			printf("MORE?");
			ch=getchar();
			if(ch!='\n')
				tch=getchar();
		}while(ch!='q' && ch!='Q' && !doneflag);
		
		/* If q or Q pressed in do-while loop prints all file*/
		while(fgets(printLineStr,100,fPtrOutput)!=NULL)
			printf("%s",printLineStr);
		
		/* File is over,safely close file pointer and */
		/* delete linesOutput.txt file */
		puts("FILE IS OVER...\n");
		fclose(fPtrOutput);
		unlink("linesOutput.txt");
		
		/* Printing the parent processes information */
		printf("%s pId: %d \n", "\n\nDone parent.", getpid());
	
		if(!doneflag)
			printf("Program is finished without CTRL + C signal\n");
		else
			printf("Program is finished with CTRL + C signal\n");
		
	}
	
	/* Program ends */
	return 0;

}
Exemplo n.º 4
0
//move.
void move_file()
{
	//mv src dest
	//pathname = src
	//parameter = dest.

	//create a local copy of the file.
	char src[128];
	char dest[128];

	strcpy(src, pathname);
	strcpy(dest, parameter);

	//1.Verify that src exist and get the inode in.
	//Open the src file for read mode.
	strcpy(pathname, src);
	strcpy(parameter, "0");
	int fd = open_file();

	//check if the file is valid or not,
	if (fd == -1)
	{
		//File error
		printf("File error!\n");
		exit(-1);
	}

	//if file is valid, get the INODE in.
	OFT* oftp_src = running->fd[fd];
	MINODE* mip_src = oftp_src->minodeptr;

	/*
	//create a file at the destination location
	strcpy(pathname, dest);
	creat_file();

	//open the file at the destination for write mode.
	strcpy(parameter, "1");
	int gd = open_file();

	//get the inode.
	OFT* oftp_dest = running->fd[fd];
	MINODE* mip_dest = oftp_dest->minodeptr;
	*/


	//check if src and dest has the same dev.???
	if (running->cwd->dev == mip_src->dev)
	{
		//Hard link dst with src.
		strcpy(pathname, src);
		strcpy(parameter, dest);
		link();

		//unlink src
		//WARNING: syntax check
		unlink();
	}

	else
	{
		//not the same dev, use copy
		strcpy(pathname, src);
		strcpy(parameter, dest);

		copy_file();

		//unlink the src
		//WARNING: syntax check.
		unlink();
	}
	



}
Exemplo n.º 5
0
int
main (int argc, char **argv)
{
  const char *filename = "test-fgetc.txt";

  /* We don't have an fgetc() function that installs an invalid parameter
     handler so far.  So install that handler here, explicitly.  */
#if HAVE_MSVC_INVALID_PARAMETER_HANDLER \
    && MSVC_INVALID_PARAMETER_HANDLING == DEFAULT_HANDLING
  gl_msvc_inval_ensure_handler ();
#endif

  /* Prepare a file.  */
  {
    const char text[] = "hello world";
    int fd = open (filename, O_RDWR | O_CREAT | O_TRUNC, 0600);
    ASSERT (fd >= 0);
    ASSERT (write (fd, text, sizeof (text)) == sizeof (text));
    ASSERT (close (fd) == 0);
  }

  /* Test that fgetc() sets errno if someone else closes the stream
     fd behind the back of stdio.  */
  {
    FILE *fp = fopen (filename, "r");
    ASSERT (fp != NULL);
    ASSERT (close (fileno (fp)) == 0);
    errno = 0;
    ASSERT (fgetc (fp) == EOF);
    ASSERT (errno == EBADF);
    ASSERT (ferror (fp));
    fclose (fp);
  }

  /* Test that fgetc() sets errno if the stream was constructed with
     an invalid file descriptor.  */
  {
    FILE *fp = fdopen (-1, "r");
    if (fp != NULL)
      {
        errno = 0;
        ASSERT (fgetc (fp) == EOF);
        ASSERT (errno == EBADF);
        ASSERT (ferror (fp));
        fclose (fp);
      }
  }
  {
    FILE *fp;
    close (99);
    fp = fdopen (99, "r");
    if (fp != NULL)
      {
        errno = 0;
        ASSERT (fgetc (fp) == EOF);
        ASSERT (errno == EBADF);
        ASSERT (ferror (fp));
        fclose (fp);
      }
  }

  /* Clean up.  */
  unlink (filename);

  return 0;
}
Exemplo n.º 6
0
int main(int argc, char **argv)
{
	int ctlfd, timerfd, alarm_nr, ret, srvfd;
	char buf[20];
	char path[32];
	struct event_queue *ev_q;

	printf("Starting alarm test\n");
	/* standard 9ns stuff: clone and read it to get our path, ending up with the
	 * ctlfd and timerfd for #A/aN/{ctl,timer}.  if you plan to fork, you can
	 * open CLOEXEC. */
	ctlfd = open("#A/clone", O_RDWR | O_CLOEXEC);
	if (ctlfd < 0) {
		perror("Can't clone an alarm");
		exit(-1);
	}
	ret = read(ctlfd, buf, sizeof(buf) - 1);
	if (ret <= 0) {
		if (!ret)
			printf("Got early EOF from ctl\n");
		else
			perror("Can't read ctl");
		exit(-1);
	}
	buf[ret] = 0;
	snprintf(path, sizeof(path), "#A/a%s/timer", buf);
	/* Don't open CLOEXEC if you want to post it to srv later */
	timerfd = open(path, O_RDWR);
	if (timerfd < 0) {
		perror("Can't open timer");
		exit(-1);
	}
	/* Since we're doing SPAM_PUBLIC later, we actually don't need a big ev_q.
	 * But someone might copy/paste this and change a flag. */
	register_ev_handler(EV_ALARM, handle_alarm, 0);
	if (!(ev_q = get_big_event_q())) {
		perror("Failed ev_q");	/* it'll actually PF if malloc fails */
		exit(-1);
	}
	ev_q->ev_vcore = 0;
	/* I think this is all the flags we need; gotta write that dissertation
	 * chapter (and event how-to)!  We may get more than one event per alarm, if
	 * we have concurrent preempts/yields. */
	ev_q->ev_flags = EVENT_IPI | EVENT_SPAM_PUBLIC;
	/* Register the ev_q for our alarm */
	ret = snprintf(path, sizeof(path), "evq %llx", ev_q);
	ret = write(ctlfd, path, ret);
	if (ret <= 0) {
		perror("Failed to write ev_q");
		exit(-1);
	}
	/* Try to set, then cancel before it should go off */
	ret = snprintf(buf, sizeof(buf), "%llx", read_tsc() + sec2tsc(1));
	ret = write(timerfd, buf, ret);
	if (ret <= 0) {
		perror("Failed to set timer");
		exit(-1);
	}
	ret = snprintf(buf, sizeof(buf), "cancel");
	ret = write(ctlfd, buf, ret);
	if (ret <= 0) {
		perror("Failed to cancel timer");
		exit(-1);
	}
	uthread_sleep(2);
	printf("No alarm should have fired yet\n");
	/* Try to set and receive */
	ret = snprintf(buf, sizeof(buf), "%llx", read_tsc() + sec2tsc(1));
	ret = write(timerfd, buf, ret);
	if (ret <= 0) {
		perror("Failed to set timer");
		exit(-1);
	}
	uthread_sleep(2);
	close(ctlfd);
	/* get crazy: post the timerfd to #s, then sleep (or even try to exit), and
	 * then echo into it remotely!  A few limitations:
	 * - if the process is DYING, you won't be able to send an event to it.
	 * - the process won't leave DYING til the srv file is removed. */
	srvfd = open("#s/alarmtest", O_WRONLY | O_CREAT | O_EXCL, 0666);
	if (srvfd < 0) {
		perror("Failed to open srv file");
		exit(-1);
	}
	ret = snprintf(buf, sizeof(buf), "%d", timerfd);
	ret = write(srvfd, buf, ret);
	if (ret <= 0) {
		perror("Failed to post timerfd");
		exit(-1);
	}
	printf("Sleeping for 10 sec, try to echo 111 > '#s/alarmtest' now!\n");
	uthread_sleep(10);
	ret = unlink("#s/alarmtest");
	if (ret < 0) {
		perror("Failed to remove timerfd from #s, proc will never be freed");
		exit(-1);
	}
	printf("Done\n");
	return 0;
}
Exemplo n.º 7
0
Arquivo: spawn.c Projeto: ytoto/uemacs
/*
 * filter a buffer through an external DOS program
 * Bound to ^X #
 */
int filter_buffer(int f, int n)
{
	int s;		/* return status from CLI */
	struct buffer *bp;	/* pointer to buffer to zot */
	char line[NLINE];	/* command line send to shell */
	char tmpnam[NFILEN];	/* place to store real file name */
	static char bname1[] = "fltinp";

	static char filnam1[] = "fltinp";
	static char filnam2[] = "fltout";

	/* don't allow this command if restricted */
	if (restflag)
		return resterr();

	if (curbp->b_mode & MDVIEW)	/* don't allow this command if      */
		return rdonly();	/* we are in read only mode     */

#if     VMS
	mlwrite("Not available under VMS");
	return FALSE;
#endif

	/* get the filter name and its args */
	if ((s = mlreply("#", line, NLINE)) != TRUE)
		return s;

	/* setup the proper file names */
	bp = curbp;
	xstrcpy(tmpnam, bp->b_fname);	/* save the original name */
	xstrcpy(bp->b_fname, bname1);	/* set it to our new one */

	/* write it out, checking for errors */
	if (writeout(filnam1) != TRUE) {
		mlwrite("(Cannot write filter file)");
		xstrcpy(bp->b_fname, tmpnam);
		return FALSE;
	}
#if     MSDOS
	strcat(line, " <fltinp >fltout");
	movecursor(term.t_nrow - 1, 0);
	TTkclose();
	shellprog(line);
	TTkopen();
	sgarbf = TRUE;
	s = TRUE;
#endif

#if     V7 | USG | BSD
	TTputc('\n');		/* Already have '\r'    */
	TTflush();
	TTclose();		/* stty to old modes    */
	TTkclose();
	strcat(line, " <fltinp >fltout");
	system(line);
	TTopen();
	TTkopen();
	TTflush();
	sgarbf = TRUE;
	s = TRUE;
#endif

	/* on failure, escape gracefully */
	if (s != TRUE || (readin(filnam2, FALSE) == FALSE)) {
		mlwrite("(Execution failed)");
		xstrcpy(bp->b_fname, tmpnam);
		unlink(filnam1);
		unlink(filnam2);
		return s;
	}

	/* reset file name */
	xstrcpy(bp->b_fname, tmpnam);	/* restore name */
	bp->b_flag |= BFCHG;	/* flag it as changed */

	/* and get rid of the temporary file */
	unlink(filnam1);
	unlink(filnam2);
	return TRUE;
}
Exemplo n.º 8
0
// Called when the stream of observations has finished to allow the implementor to perform clean-up tasks.
// This method is optional.
void externalTraceProcessor_File::obsFinished() {
  //cout << "externalTraceProcessor_File::obsFinished() finished="<<finished<<endl;
  // Only perform finishing code if we haven't already finished
  if(finished) return;
  finished = true;
  
  // We're done writing the trace file, so close the stream
  traceFile.close();
  
  // Execute the processing application
  ostringstream s; 
  s << processorFName;
  for(list<string>::iterator b=beforeParams.begin(); b!=beforeParams.end(); b++) s << " \""<<*b<<"\"";
  s << " \""<<obsFName<<"\"";
  for(list<string>::iterator a=afterParams.begin(); a!=afterParams.end(); a++) s << " \""<<*a<<"\"";
  //cout << "Command = "<<s.str()<<endl;

  // In case the processor executable is linked with Sight, unset the mutex environment variables from 
  // LoadTimeRegistry to make sure that they don't leak to the layout process
  common::LoadTimeRegistry::liftMutexes();
  
  FILE* out = popen(s.str().c_str(), "r");
  if(out == NULL) { cerr << "Failed to run command \""<<s.str()<<"\"!"<<endl; assert(0); }
  
  // Restore the LoadTimeRegistry mutexes
  common::LoadTimeRegistry::restoreMutexes();

  // Read out the trace produced by the processor
  char line[10000];
  while(fgets(line, 10000, out)) {
    //cout << "line=\""<<line<<"\""<<endl;
    // Split the line into its individual terms
    sight::common::escapedStr es(string(line), " ", sight::common::escapedStr::escaped);
    vector<string> terms = es.unescapeSplit(" ");

    map<string, string> ctxt, obs;
    map<string, anchor> obsAnchor;

    // Iterate over each term of this observation, adding each one into this observation's context, trace observation or anchors
    for(vector<string>::iterator t=terms.begin(); t!=terms.end(); t++) {
      //cout << "t=\""<<*t<<"\""<<endl;
      
      // Split the term into the key and the value
      sight::common::escapedStr es(string(*t), ":", sight::common::escapedStr::escaped);
      vector<string> kv = es.unescapeSplit(":");
      assert(kv.size()==3);
      string type=kv[0];
      string key =kv[1];
      string val =kv[2];

      // Identify the type of this term
      if(type == "ctxt") ctxt[key] = val;
      else if(type=="obs") obs[key] = val;
      else obsAnchor[key] = anchor(attrValue::parseInt(val));
    }
    
    // Emit the observation
    /*cout << "ctxt="<<endl;
    for(map<string, string>::iterator c=ctxt.begin(); c!=ctxt.end(); c++)
      cout << "    "<<c->first<<" => "<<c->second<<endl;*/
    emitObservation(-1, ctxt, obs, obsAnchor);
  }
  //cout << "done"<<endl;
  pclose(out);

  // Delete the file that was provided as input to the command since it is no longer needed
  unlink(obsFName.c_str());
  
  // Inform this trace's observers that it has finished
  traceObserver::obsFinished();
}
Exemplo n.º 9
0
int main(void) {
  size_t num_bytes = sysconf(_SC_PAGESIZE);
  int fd = open("temp", O_CREAT | O_EXCL | O_RDWR);
  int* rpage;

  unlink("temp");

  test_assert(fd >= 0);

  int magic = 0x5a5a5a5a;
  size_t i;
  for (i = 0; i < 3 * num_bytes / sizeof(magic); ++i) {
    pwrite64(fd, &magic, sizeof(magic), i * sizeof(magic));
  }

  rpage = mmap(NULL, num_bytes, PROT_READ, MAP_SHARED, fd, 0);
  atomic_printf("rpage:%p\n", rpage);
  test_assert(rpage != MAP_FAILED);

  magic = 0xa5a5a5a5;
  for (i = 0; i < num_bytes / sizeof(magic); ++i) {
    pwrite64(fd, &magic, sizeof(magic), i * sizeof(magic));
  }

  check_mapping(rpage, 0xa5a5a5a5, num_bytes / sizeof(*rpage));

  magic = 0x5a5a5a5a;
  for (i = 0; i < num_bytes / sizeof(magic); ++i) {
    pwrite64(fd, &magic, sizeof(magic), i * sizeof(magic));
  }

  check_mapping(rpage, 0x5a5a5a5a, num_bytes / sizeof(*rpage));

  magic = 0xa5a5a5a5;
  for (i = 0; i < num_bytes / sizeof(magic); ++i) {
    pwrite64(fd, &magic, sizeof(magic), num_bytes + i * sizeof(magic));
  }

  check_mapping(rpage, 0x5a5a5a5a, num_bytes / sizeof(*rpage));

  magic = 0xdeadbeef;
  pwrite64(fd, &magic, sizeof(magic), num_bytes / 2);

  test_assert(rpage[num_bytes / (sizeof(magic) * 2)] == magic);
  test_assert(rpage[0] != magic);

  pwrite64(fd, &magic, sizeof(magic), num_bytes - 2);
  test_assert(rpage[num_bytes / sizeof(magic) - 1] == (int)0xbeef5a5a);

  rpage = mremap(rpage, num_bytes, 5 * num_bytes, MREMAP_MAYMOVE);
  for (i = 3 * num_bytes / sizeof(magic); i < 5 * num_bytes / sizeof(magic);
       ++i) {
    pwrite64(fd, &magic, sizeof(magic), i * sizeof(magic));
  }
  check_mapping(&rpage[(3 * num_bytes) / sizeof(magic)], 0xdeadbeef,
                2 * num_bytes / sizeof(*rpage));

  munmap(rpage, 5 * num_bytes);

  // The case when all pages have been unmapped is special in the
  // implementation - make sure it gets sufficient coverage
  write(fd, &magic, sizeof(magic));
  write(fd, &magic, sizeof(magic));

  rpage = mmap(NULL, num_bytes, PROT_READ, MAP_SHARED, fd, 0);
  atomic_printf("rpage:%p\n", rpage);
  test_assert(rpage != MAP_FAILED);

  // This tests both that the monitor gets activated again if the page is
  // remapped and that `write` works on a monitored page.
  lseek(fd, 0, SEEK_SET);
  magic = 0xb6b6b6b6;
  for (i = 0; i < num_bytes / sizeof(magic); ++i) {
    write(fd, &magic, sizeof(magic));
  }
  check_mapping(rpage, magic, num_bytes / sizeof(*rpage));

  atomic_puts("EXIT-SUCCESS");

  return 0;
}
Exemplo n.º 10
0
int
main(int argc, char **argv)
{
  int i;
  sigset_t set;
#if ENABLE_LINUXDVB
  uint32_t adapter_mask;
#endif
  int  log_level   = LOG_INFO;
  int  log_options = TVHLOG_OPT_MILLIS | TVHLOG_OPT_STDERR | TVHLOG_OPT_SYSLOG;
  const char *log_debug = NULL, *log_trace = NULL;
  char buf[512];

  main_tid = pthread_self();

  /* Setup global mutexes */
  pthread_mutex_init(&ffmpeg_lock, NULL);
  pthread_mutex_init(&fork_lock, NULL);
  pthread_mutex_init(&global_lock, NULL);
  pthread_mutex_init(&atomic_lock, NULL);
  pthread_cond_init(&gtimer_cond, NULL);

  /* Defaults */
  tvheadend_webui_port      = 9981;
  tvheadend_webroot         = NULL;
  tvheadend_htsp_port       = 9982;
  tvheadend_htsp_port_extra = 0;

  /* Command line options */
  int         opt_help         = 0,
              opt_version      = 0,
              opt_fork         = 0,
              opt_firstrun     = 0,
              opt_stderr       = 0,
              opt_syslog       = 0,
              opt_uidebug      = 0,
              opt_abort        = 0,
              opt_noacl        = 0,
              opt_fileline     = 0,
              opt_threadid     = 0,
              opt_ipv6         = 0,
              opt_tsfile_tuner = 0,
              opt_dump         = 0;
  const char *opt_config       = NULL,
             *opt_user         = NULL,
             *opt_group        = NULL,
             *opt_logpath      = NULL,
             *opt_log_debug    = NULL,
             *opt_log_trace    = NULL,
             *opt_pidpath      = "/var/run/tvheadend.pid",
#if ENABLE_LINUXDVB
             *opt_dvb_adapters = NULL,
#endif
             *opt_bindaddr     = NULL,
             *opt_subscribe    = NULL;
  str_list_t  opt_tsfile       = { .max = 10, .num = 0, .str = calloc(10, sizeof(char*)) };
  cmdline_opt_t cmdline_opts[] = {
    {   0, NULL,        "Generic Options",         OPT_BOOL, NULL         },
    { 'h', "help",      "Show this page",          OPT_BOOL, &opt_help    },
    { 'v', "version",   "Show version infomation", OPT_BOOL, &opt_version },

    {   0, NULL,        "Service Configuration",   OPT_BOOL, NULL         },
    { 'c', "config",    "Alternate config path",   OPT_STR,  &opt_config  },
    { 'f', "fork",      "Fork and run as daemon",  OPT_BOOL, &opt_fork    },
    { 'u', "user",      "Run as user",             OPT_STR,  &opt_user    },
    { 'g', "group",     "Run as group",            OPT_STR,  &opt_group   },
    { 'p', "pid",       "Alternate pid path",      OPT_STR,  &opt_pidpath },
    { 'C', "firstrun",  "If no user account exists then create one with\n"
	                      "no username and no password. Use with care as\n"
	                      "it will allow world-wide administrative access\n"
	                      "to your Tvheadend installation until you edit\n"
	                      "the access-control from within the Tvheadend UI",
      OPT_BOOL, &opt_firstrun },
#if ENABLE_LINUXDVB
    { 'a', "adapters",  "Only use specified DVB adapters (comma separated)",
      OPT_STR, &opt_dvb_adapters },
#endif
    {   0, NULL,         "Server Connectivity",    OPT_BOOL, NULL         },
    { '6', "ipv6",       "Listen on IPv6",         OPT_BOOL, &opt_ipv6    },
    { 'b', "bindaddr",   "Specify bind address",   OPT_STR,  &opt_bindaddr},
    {   0, "http_port",  "Specify alternative http port",
      OPT_INT, &tvheadend_webui_port },
    {   0, "http_root",  "Specify alternative http webroot",
      OPT_STR, &tvheadend_webroot },
    {   0, "htsp_port",  "Specify alternative htsp port",
      OPT_INT, &tvheadend_htsp_port },
    {   0, "htsp_port2", "Specify extra htsp port",
      OPT_INT, &tvheadend_htsp_port_extra },

    {   0, NULL,        "Debug Options",           OPT_BOOL, NULL         },
    { 'd', "stderr",    "Enable debug on stderr",  OPT_BOOL, &opt_stderr  },
    { 's', "syslog",    "Enable debug to syslog",  OPT_BOOL, &opt_syslog  },
    { 'l', "logfile",   "Enable debug to file",    OPT_STR,  &opt_logpath },
    {   0, "debug",     "Enable debug subsystems", OPT_STR,  &opt_log_debug },
#if ENABLE_TRACE
    {   0, "trace",     "Enable trace subsystems", OPT_STR,  &opt_log_trace },
#endif
    {   0, "fileline",  "Add file and line numbers to debug", OPT_BOOL, &opt_fileline },
    {   0, "threadid",  "Add the thread ID to debug", OPT_BOOL, &opt_threadid },
    {   0, "uidebug",   "Enable webUI debug (non-minified JS)", OPT_BOOL, &opt_uidebug },
    { 'A', "abort",     "Immediately abort",       OPT_BOOL, &opt_abort   },
    { 'D', "dump",      "Enable coredumps for daemon", OPT_BOOL, &opt_dump },
    {   0, "noacl",     "Disable all access control checks",
      OPT_BOOL, &opt_noacl },
    { 'j', "join",      "Subscribe to a service permanently",
      OPT_STR, &opt_subscribe },


    { 0, NULL, "TODO: testing", OPT_BOOL, NULL },
    { 0, "tsfile_tuners", "Number of tsfile tuners", OPT_INT, &opt_tsfile_tuner },
    { 0, "tsfile", "tsfile input (mux file)", OPT_STR_LIST, &opt_tsfile },

  };

  /* Get current directory */
  tvheadend_cwd = dirname(dirname(tvh_strdupa(argv[0])));

  /* Set locale */
  setlocale(LC_ALL, "");
  setlocale(LC_NUMERIC, "C");

  /* make sure the timezone is set */
  tzset();

  /* Process command line */
  for (i = 1; i < argc; i++) {

    /* Find option */
    cmdline_opt_t *opt
      = cmdline_opt_find(cmdline_opts, ARRAY_SIZE(cmdline_opts), argv[i]);
    if (!opt)
      show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts),
                 "invalid option specified [%s]", argv[i]);

    /* Process */
    if (opt->type == OPT_BOOL)
      *((int*)opt->param) = 1;
    else if (++i == argc)
      show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts),
                 "option %s requires a value", opt->lopt);
    else if (opt->type == OPT_INT)
      *((int*)opt->param) = atoi(argv[i]);
    else if (opt->type == OPT_STR_LIST) {
      str_list_t *strl = opt->param;
      if (strl->num < strl->max)
        strl->str[strl->num++] = argv[i];
    }
    else
      *((char**)opt->param) = argv[i];

    /* Stop processing */
    if (opt_help)
      show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts), NULL);
    if (opt_version)
      show_version(argv[0]);
  }

  /* Additional cmdline processing */
#if ENABLE_LINUXDVB
  if (!opt_dvb_adapters) {
    adapter_mask = ~0;
  } else {
    char *p, *e;
    char *r = NULL;
    char *dvb_adapters = strdup(opt_dvb_adapters);
    adapter_mask = 0x0;
    p = strtok_r(dvb_adapters, ",", &r);
    while (p) {
      int a = strtol(p, &e, 10);
      if (*e != 0 || a < 0 || a > 31) {
        tvhlog(LOG_ERR, "START", "Invalid adapter number '%s'", p);
        free(dvb_adapters);
        return 1;
      }
      adapter_mask |= (1 << a);
      p = strtok_r(NULL, ",", &r);
    }
    free(dvb_adapters);
    if (!adapter_mask) {
      tvhlog(LOG_ERR, "START", "No adapters specified!");
      return 1;
    }
  }
#endif
  if (tvheadend_webroot) {
    char *tmp;
    if (*tvheadend_webroot == '/')
      tmp = strdup(tvheadend_webroot);
    else {
      tmp = malloc(strlen(tvheadend_webroot)+2);
      *tmp = '/';
      strcpy(tmp+1, tvheadend_webroot);
    }
    if (tmp[strlen(tmp)-1] == '/')
      tmp[strlen(tmp)-1] = '\0';
    tvheadend_webroot = tmp;
  }
  tvheadend_webui_debug = opt_uidebug;

  /* Setup logging */
  if (isatty(2))
    log_options |= TVHLOG_OPT_DECORATE;
  if (opt_stderr || opt_syslog || opt_logpath) {
    if (!opt_log_trace && !opt_log_debug)
      log_debug      = "all";
    log_level      = LOG_DEBUG;
    if (opt_stderr)
      log_options   |= TVHLOG_OPT_DBG_STDERR;
    if (opt_syslog)
      log_options   |= TVHLOG_OPT_DBG_SYSLOG;
    if (opt_logpath)
      log_options   |= TVHLOG_OPT_DBG_FILE;
  }
  if (opt_fileline)
    log_options |= TVHLOG_OPT_FILELINE;
  if (opt_threadid)
    log_options |= TVHLOG_OPT_THREAD;
  if (opt_log_trace) {
    log_level  = LOG_TRACE;
    log_trace  = opt_log_trace;
  }
  if (opt_log_debug)
    log_debug  = opt_log_debug;
    
  tvhlog_init(log_level, log_options, opt_logpath);
  tvhlog_set_debug(log_debug);
  tvhlog_set_trace(log_trace);
 
  signal(SIGPIPE, handle_sigpipe); // will be redundant later

  /* Daemonise */
  if(opt_fork) {
    const char *homedir;
    gid_t gid;
    uid_t uid;
    struct group  *grp = getgrnam(opt_group ?: "video");
    struct passwd *pw  = opt_user ? getpwnam(opt_user) : NULL;
    FILE   *pidfile    = fopen(opt_pidpath, "w+");

    if(grp != NULL) {
      gid = grp->gr_gid;
    } else {
      gid = 1;
    }

    if (pw != NULL) {
      if (getuid() != pw->pw_uid) {
        gid_t glist[10];
        int gnum;
        gnum = get_user_groups(pw, glist, 10);
        if (setgroups(gnum, glist)) {
          tvhlog(LOG_ALERT, "START",
                 "setgroups() failed, do you have permission?");
          return 1;
        }
      }
      uid     = pw->pw_uid;
      homedir = pw->pw_dir;
      setenv("HOME", homedir, 1);
    } else {
      uid = 1;
    }
    if ((getgid() != gid) && setgid(gid)) {
      tvhlog(LOG_ALERT, "START",
             "setgid() failed, do you have permission?");
      return 1;
    }
    if ((getuid() != uid) && setuid(uid)) {
      tvhlog(LOG_ALERT, "START",
             "setuid() failed, do you have permission?");
      return 1;
    }

    if(daemon(0, 0)) {
      exit(2);
    }
    if(pidfile != NULL) {
      fprintf(pidfile, "%d\n", getpid());
      fclose(pidfile);
    }

    /* Make dumpable */
    if (opt_dump) {
#ifdef PLATFORM_LINUX
      if (chdir("/tmp"))
        tvhwarn("START", "failed to change cwd to /tmp");
      prctl(PR_SET_DUMPABLE, 1);
#else
      tvhwarn("START", "Coredumps not implemented on your platform");
#endif
    }

    umask(0);
  }

  tvheadend_running = 1;

  /* Start log thread (must be done post fork) */
  tvhlog_start();

  /* Alter logging */
  if (opt_fork)
    tvhlog_options &= ~TVHLOG_OPT_STDERR;
  if (!isatty(2))
    tvhlog_options &= ~TVHLOG_OPT_DECORATE;
  
  /* Initialise clock */
  pthread_mutex_lock(&global_lock);
  time(&dispatch_clock);

  /* Signal handling */
  sigfillset(&set);
  sigprocmask(SIG_BLOCK, &set, NULL);
  trap_init(argv[0]);
  
  /* Initialise configuration */
  uuid_init();
  idnode_init();
  config_init(opt_config);

  /**
   * Initialize subsystems
   */
  
  api_init();

  fsmonitor_init();

#if ENABLE_LIBAV
  libav_init();
  transcoding_init();
#endif

  imagecache_init();

  service_init();

#if ENABLE_TSFILE
  if(opt_tsfile.num) {
    tsfile_init(opt_tsfile_tuner ?: opt_tsfile.num);
    for (i = 0; i < opt_tsfile.num; i++)
      tsfile_add_file(opt_tsfile.str[i]);
  }
#endif
#if ENABLE_MPEGTS_DVB
  dvb_network_init();
#endif
#if ENABLE_IPTV
  iptv_init();
#endif
#if ENABLE_LINUXDVB
  linuxdvb_init(adapter_mask);
#endif

  channel_init();

  subscription_init();

  access_init(opt_firstrun, opt_noacl);

#if ENABLE_TIMESHIFT
  timeshift_init();
#endif

  http_client_init();
  tcp_server_init(opt_ipv6);
  http_server_init(opt_bindaddr);
  webui_init();

  service_mapper_init();

  descrambler_init();

  epggrab_init();
  epg_init();

  dvr_init();

  htsp_init(opt_bindaddr);


  if(opt_subscribe != NULL)
    subscription_dummy_join(opt_subscribe, 1);

  avahi_init();

  epg_updated(); // cleanup now all prev ref's should have been created

  pthread_mutex_unlock(&global_lock);

  /**
   * Wait for SIGTERM / SIGINT, but only in this thread
   */

  sigemptyset(&set);
  sigaddset(&set, SIGTERM);
  sigaddset(&set, SIGINT);

  signal(SIGTERM, doexit);
  signal(SIGINT, doexit);

  pthread_sigmask(SIG_UNBLOCK, &set, NULL);

  tvhlog(LOG_NOTICE, "START", "HTS Tvheadend version %s started, "
         "running as PID:%d UID:%d GID:%d, CWD:%s CNF:%s",
         tvheadend_version,
         getpid(), getuid(), getgid(), getcwd(buf, sizeof(buf)),
         hts_settings_get_root());

  if(opt_abort)
    abort();

  mainloop();

  tvhftrace("main", htsp_done);
  tvhftrace("main", http_server_done);
  tvhftrace("main", webui_done);
  tvhftrace("main", http_client_done);
  tvhftrace("main", fsmonitor_done);
#if ENABLE_MPEGTS_DVB
  tvhftrace("main", dvb_network_done);
#endif
#if ENABLE_IPTV
  tvhftrace("main", iptv_done);
#endif
#if ENABLE_LINUXDVB
  tvhftrace("main", linuxdvb_done);
#endif

  // Note: the locking is obviously a bit redundant, but without
  //       we need to disable the gtimer_arm call in epg_save()
  pthread_mutex_lock(&global_lock);
  tvhftrace("main", epg_save);

#if ENABLE_TIMESHIFT
  tvhftrace("main", timeshift_term);
#endif
  pthread_mutex_unlock(&global_lock);

  tvhftrace("main", epggrab_done);
  tvhftrace("main", tcp_server_done);
  tvhftrace("main", descrambler_done);
  tvhftrace("main", service_mapper_done);
  tvhftrace("main", service_done);
  tvhftrace("main", channel_done);
  tvhftrace("main", dvr_done);
  tvhftrace("main", subscription_done);
  tvhftrace("main", access_done);
  tvhftrace("main", epg_done);
  tvhftrace("main", avahi_done);
  tvhftrace("main", imagecache_done);
  tvhftrace("main", idnode_done);
  tvhftrace("main", lang_code_done);
  tvhftrace("main", api_done);
  tvhftrace("main", config_done);
  tvhftrace("main", hts_settings_done);
  tvhftrace("main", dvb_done);
  tvhftrace("main", lang_str_done);

  tvhlog(LOG_NOTICE, "STOP", "Exiting HTS Tvheadend");
  tvhlog_end();

  if(opt_fork)
    unlink(opt_pidpath);
    
  free(opt_tsfile.str);

  return 0;
}
Exemplo n.º 11
0
BOOL DeleteFileA(LPCSTR lpFileName)
{
	int status;
	status = unlink(lpFileName);
	return (status != -1) ? TRUE : FALSE;
}
void FAST_FUNC data_extract_all(archive_handle_t *archive_handle)
{
	file_header_t *file_header = archive_handle->file_header;
	int dst_fd;
	int res;

	if (archive_handle->ah_flags & ARCHIVE_CREATE_LEADING_DIRS) {
		char *slash = strrchr(file_header->name, '/');
		if (slash) {
			*slash = '\0';
			bb_make_directory(file_header->name, -1, FILEUTILS_RECUR);
			*slash = '/';
		}
	}

	if (archive_handle->ah_flags & ARCHIVE_UNLINK_OLD) {
		/* Remove the entry if it exists */
		if ((!S_ISDIR(file_header->mode))
		 && (unlink(file_header->name) == -1)
		 && (errno != ENOENT)
		) {
			bb_perror_msg_and_die("can't remove old file %s",
					file_header->name);
		}
	}
	else if (archive_handle->ah_flags & ARCHIVE_EXTRACT_NEWER) {
		/* Remove the existing entry if its older than the extracted entry */
		struct stat existing_sb;
		if (lstat(file_header->name, &existing_sb) == -1) {
			if (errno != ENOENT) {
				bb_perror_msg_and_die("can't stat old file");
			}
		}
		else if (existing_sb.st_mtime >= file_header->mtime) {
			if (!(archive_handle->ah_flags & ARCHIVE_EXTRACT_QUIET)) {
				bb_error_msg("%s not created: newer or "
					"same age file exists", file_header->name);
			}
			data_skip(archive_handle);
			return;
		}
		else if ((unlink(file_header->name) == -1) && (errno != EISDIR)) {
			bb_perror_msg_and_die("can't remove old file %s",
					file_header->name);
		}
	}

	/* Handle hard links separately
	 * We identified hard links as regular files of size 0 with a symlink */
	if (S_ISREG(file_header->mode)
	 && file_header->link_target
	 && file_header->size == 0
	) {
		/* hard link */
		res = link(file_header->link_target, file_header->name);
		if ((res == -1) && !(archive_handle->ah_flags & ARCHIVE_EXTRACT_QUIET)) {
			bb_perror_msg("can't create %slink "
					"from %s to %s", "hard",
					file_header->name,
					file_header->link_target);
		}
	} else {
		/* Create the filesystem entry */
		switch (file_header->mode & S_IFMT) {
		case S_IFREG: {
			/* Regular file */
			int flags = O_WRONLY | O_CREAT | O_EXCL;
			if (archive_handle->ah_flags & ARCHIVE_O_TRUNC)
				flags = O_WRONLY | O_CREAT | O_TRUNC;
			dst_fd = xopen3(file_header->name,
				flags,
				file_header->mode
				);
			bb_copyfd_exact_size(archive_handle->src_fd, dst_fd, file_header->size);
			close(dst_fd);
			break;
		}
		case S_IFDIR:
			res = mkdir(file_header->name, file_header->mode);
			if ((res == -1)
			 && (errno != EISDIR) /* btw, Linux doesn't return this */
			 && (errno != EEXIST)
			 && !(archive_handle->ah_flags & ARCHIVE_EXTRACT_QUIET)
			) {
				bb_perror_msg("can't make dir %s", file_header->name);
			}
			break;
		case S_IFLNK:
			/* Symlink */
			res = symlink(file_header->link_target, file_header->name);
			if ((res == -1)
			 && !(archive_handle->ah_flags & ARCHIVE_EXTRACT_QUIET)
			) {
				bb_perror_msg("can't create %slink "
					"from %s to %s", "sym",
					file_header->name,
					file_header->link_target);
			}
			break;
		case S_IFSOCK:
		case S_IFBLK:
		case S_IFCHR:
		case S_IFIFO:
			res = mknod(file_header->name, file_header->mode, file_header->device);
			if ((res == -1)
			 && !(archive_handle->ah_flags & ARCHIVE_EXTRACT_QUIET)
			) {
				bb_perror_msg("can't create node %s", file_header->name);
			}
			break;
		default:
			bb_error_msg_and_die("unrecognized file type");
		}
	}

	if (!(archive_handle->ah_flags & ARCHIVE_DONT_RESTORE_OWNER)) {
#if ENABLE_FEATURE_TAR_UNAME_GNAME
		if (!(archive_handle->ah_flags & ARCHIVE_NUMERIC_OWNER)) {
			uid_t uid = file_header->uid;
			gid_t gid = file_header->gid;

			if (file_header->tar__uname) {
//TODO: cache last name/id pair?
				struct passwd *pwd = getpwnam(file_header->tar__uname);
				if (pwd) uid = pwd->pw_uid;
			}
			if (file_header->tar__gname) {
				struct group *grp = getgrnam(file_header->tar__gname);
				if (grp) gid = grp->gr_gid;
			}
			/* GNU tar 1.15.1 uses chown, not lchown */
			chown(file_header->name, uid, gid);
		} else
#endif
			chown(file_header->name, file_header->uid, file_header->gid);
	}
	if (!S_ISLNK(file_header->mode)) {
		/* uclibc has no lchmod, glibc is even stranger -
		 * it has lchmod which seems to do nothing!
		 * so we use chmod... */
		if (!(archive_handle->ah_flags & ARCHIVE_DONT_RESTORE_PERM)) {
			chmod(file_header->name, file_header->mode);
		}
		/* same for utime */
		if (archive_handle->ah_flags & ARCHIVE_RESTORE_DATE) {
			struct timeval t[2];

			t[1].tv_sec = t[0].tv_sec = file_header->mtime;
			t[1].tv_usec = t[0].tv_usec = 0;
			utimes(file_header->name, t);
		}
	}
}
Exemplo n.º 13
0
int Q_unlink (const char *path)
{
	return unlink(path);
}
Exemplo n.º 14
0
int main(int ac, char **av)
{
	int rwfd;
	int i;
	int j;
	int c;

	off_t file_size = 1 * 1024 * 1024 * 1024;
	int first_stage = WRITE;
	struct io_oper *oper;
	int status = 0;
	int num_files = 0;
	int open_fds = 0;
	struct thread_info *t;

	page_size_mask = getpagesize() - 1;

	while (1) {
		c = getopt(ac, av, "a:b:c:C:m:s:r:d:i:I:o:t:lLnhOSxvu");
		if (c < 0)
			break;

		switch (c) {
		case 'a':
			page_size_mask = parse_size(optarg, 1024);
			page_size_mask--;
			break;
		case 'c':
			num_contexts = atoi(optarg);
			break;
		case 'C':
			context_offset = parse_size(optarg, 1024 * 1024);
		case 'b':
			max_io_submit = atoi(optarg);
			break;
		case 's':
			file_size = parse_size(optarg, 1024 * 1024);
			break;
		case 'd':
			depth = atoi(optarg);
			break;
		case 'r':
			rec_len = parse_size(optarg, 1024);
			break;
		case 'i':
			io_iter = atoi(optarg);
			break;
		case 'I':
			iterations = atoi(optarg);
			break;
		case 'n':
			fsync_stages = 0;
			break;
		case 'l':
			latency_stats = 1;
			break;
		case 'L':
			completion_latency_stats = 1;
			break;
		case 'm':
			if (!strcmp(optarg, "shm")) {
				fprintf(stderr, "using ipc shm\n");
				use_shm = USE_SHM;
			} else if (!strcmp(optarg, "shmfs")) {
				fprintf(stderr, "using /dev/shm for buffers\n");
				use_shm = USE_SHMFS;
			}
			break;
		case 'o':
			i = atoi(optarg);
			stages |= 1 << i;
			fprintf(stderr, "adding stage %s\n", stage_name(i));
			break;
		case 'O':
			o_direct = O_DIRECT;
			break;
		case 'S':
			o_sync = O_SYNC;
			break;
		case 't':
			num_threads = atoi(optarg);
			break;
		case 'x':
			stonewall = 0;
			break;
		case 'u':
			unlink_files = 1;
			break;
		case 'v':
			verify = 1;
			break;
		case 'h':
		default:
			print_usage();
			exit(1);
		}
	}

	/*
	 * make sure we don't try to submit more I/O than we have allocated
	 * memory for
	 */
	if (depth < io_iter) {
		io_iter = depth;
		fprintf(stderr, "dropping io_iter to %d\n", io_iter);
	}

	if (optind >= ac) {
		print_usage();
		exit(1);
	}

	num_files = ac - optind;

	if (num_threads > (num_files * num_contexts)) {
		num_threads = num_files * num_contexts;
		fprintf(stderr,
			"dropping thread count to the number of contexts %d\n",
			num_threads);
	}

	t = malloc(num_threads * sizeof(*t));
	if (!t) {
		perror("malloc");
		exit(1);
	}
	global_thread_info = t;

	/* by default, allow a huge number of iocbs to be sent towards
	 * io_submit
	 */
	if (!max_io_submit)
		max_io_submit = num_files * io_iter * num_contexts;

	/*
	 * make sure we don't try to submit more I/O than max_io_submit allows
	 */
	if (max_io_submit < io_iter) {
		io_iter = max_io_submit;
		fprintf(stderr, "dropping io_iter to %d\n", io_iter);
	}

	if (!stages) {
		stages =
		    (1 << WRITE) | (1 << READ) | (1 << RREAD) | (1 << RWRITE);
	} else {
		for (i = 0; i < LAST_STAGE; i++) {
			if (stages & (1 << i)) {
				first_stage = i;
				fprintf(stderr, "starting with %s\n",
					stage_name(i));
				break;
			}
		}
	}

	if (file_size < num_contexts * context_offset) {
		fprintf(stderr, "file size %ld too small for %d contexts\n",
			(long)file_size, num_contexts);
		exit(1);
	}

	fprintf(stderr, "file size %ldMB, record size %ldKB, depth %d, "
		"I/O per iteration %d\n",
		(long)(file_size / (1024 * 1024)),
		rec_len / 1024, depth, io_iter);
	fprintf(stderr, "max io_submit %d, buffer alignment set to %luKB\n",
		max_io_submit, (page_size_mask + 1) / 1024);
	fprintf(stderr, "threads %d files %d contexts %d context offset %ldMB "
		"verification %s\n", num_threads, num_files, num_contexts,
		(long)(context_offset / (1024 * 1024)), verify ? "on" : "off");
	/* open all the files and do any required setup for them */
	for (i = optind; i < ac; i++) {
		int thread_index;
		for (j = 0; j < num_contexts; j++) {
			thread_index = open_fds % num_threads;
			open_fds++;

			rwfd =
			    open(av[i], O_CREAT | O_RDWR | o_direct | o_sync,
				 0600);
			if (rwfd == -1) {
				fprintf(stderr,
					"error while creating file %s: %s",
					av[i], strerror(errno));
				exit(1);
			}

			oper =
			    create_oper(rwfd, first_stage, j * context_offset,
					file_size - j * context_offset, rec_len,
					depth, io_iter, av[i]);
			if (!oper) {
				fprintf(stderr, "error in create_oper\n");
				exit(-1);
			}
			oper_list_add(oper, &t[thread_index].active_opers);
			t[thread_index].num_files++;
		}
	}
	if (setup_shared_mem(num_threads, num_files * num_contexts,
			     depth, rec_len, max_io_submit)) {
		exit(1);
	}
	for (i = 0; i < num_threads; i++) {
		if (setup_ious
		    (&t[i], t[i].num_files, depth, rec_len, max_io_submit))
			exit(1);
	}
	if (num_threads > 1) {
		printf("Running multi thread version num_threads:%d\n",
		       num_threads);
		run_workers(t, num_threads);
	} else {
		printf("Running single thread version \n");
		status = worker(t);
	}
	if (unlink_files) {
		for (i = optind; i < ac; i++) {
			printf("Cleaning up file %s \n", av[i]);
			unlink(av[i]);
		}
	}

	if (status) {
		exit(1);
	}
	return status;
}
Exemplo n.º 15
0
/**
 * Main program.  Returns 1 if all programs run successfully, 0 if
 * something failed and -1 if there was an error running programs.
 */
int main(int argc, char *argv[]) {
	int retcode;
	struct sigaction zig;
	pid_t pid;
	char *c;

	/* Check parameters */
	if (argc < 2) {
		fprintf(stderr, "Usage: %s test_prog\n", argv[0]);
		return 1;
	}

	if (argc > 2 && strcmp(argv[2], "--leader") == 0) {
		pounder_fprintf(stdout, "Logging this test output to %s/POUNDERLOG.\n",
			getenv("POUNDER_LOGDIR"));
		is_leader = 1;
		record_pid();
	}

	progname = argv[0];

	/* Set up signals */
	memset(&zig, 0x00, sizeof(zig));
	zig.sa_handler = jump_out;
	sigaction(SIGHUP, &zig, NULL);
	sigaction(SIGINT, &zig, NULL);
	sigaction(SIGTERM, &zig, NULL);

	if (is_directory(argv[1])) {
		retcode = process_dir(argv[1]);
	} else {
		if (is_executable(argv[1])) {
			c = rindex(argv[1], '/');
			c++;

			// Start the test
			pid = spawn_test(argv[1]);
			if (pid < 0) {
				perror("fork");
				retcode = -1;
				goto out;
			}

			// Track the test
			note_process(pid, argv[1]);
			if (wait_for_pids() == 0) {
				retcode = 1;
			} else {
				retcode = 0;
			}
		} else {
			pounder_fprintf(stderr, "%s: Not a directory or a test.\n",
				argv[1]);
			retcode = -1;
		}
	}

out:
	kill_daemons();
	wait_for_daemons();
	if (is_leader) {
		if (retcode == 0) {
			pounder_fprintf(stdout, "%s: %s.\n", argv[1], pass_msg);
		} else if (retcode < 0 || retcode == 255) {
			pounder_fprintf(stdout, "%s: %s with code %d.\n",
				argv[1], abort_msg, retcode);
		} else {
			pounder_fprintf(stdout, "%s: %s with code %d.\n",
				argv[1], fail_msg, retcode);
		}
		unlink(pidfile);
	}
	exit(retcode);
}
Exemplo n.º 16
0
/* __CFWriteBytesToFileWithAtomicity is a "safe save" facility. Write the bytes using the specified mode on the file to the provided URL. If the atomic flag is true, try to do it in a fashion that will enable a safe save.
 */
static Boolean __CFWriteBytesToFileWithAtomicity(CFURLRef url, const void *bytes, int length, SInt32 mode, Boolean atomic) {
    int fd = -1;
    char auxPath[CFMaxPathSize + 16];
    char cpath[CFMaxPathSize];
    uid_t owner = getuid();
    gid_t group = getgid();
    Boolean writingFileAsRoot = ((getuid() != geteuid()) && (geteuid() == 0));
    
    if (!CFURLGetFileSystemRepresentation(url, true, (uint8_t *)cpath, CFMaxPathSize)) {
        return false;
    }
    
    if (-1 == mode || writingFileAsRoot) {
        struct stat statBuf;
        if (0 == stat(cpath, &statBuf)) {
            mode = statBuf.st_mode;
            owner = statBuf.st_uid;
            group = statBuf.st_gid;
        } else {
            mode = 0664;
            if (writingFileAsRoot && (0 == strncmp(cpath, "/Library/Preferences", 20))) {
                owner = geteuid();
                group = 80;
            }
        }
    }
    
    if (atomic) {
        CFURLRef dir = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorSystemDefault, url);
        CFURLRef tempFile = CFURLCreateCopyAppendingPathComponent(kCFAllocatorSystemDefault, dir, CFSTR("cf#XXXXX"), false);
        CFRelease(dir);
        if (!CFURLGetFileSystemRepresentation(tempFile, true, (uint8_t *)auxPath, CFMaxPathSize)) {
            CFRelease(tempFile);
            return false;
        }
        CFRelease(tempFile);
        fd = mkstemp(auxPath);
    } else {
        fd = open(cpath, O_WRONLY|O_CREAT|O_TRUNC, mode);
    }
    
    if (fd < 0) return false;
    
    if (length && (write(fd, bytes, length) != length || fsync(fd) < 0)) {
        int saveerr = thread_errno();
        close(fd);
        if (atomic)
            unlink(auxPath);
        thread_set_errno(saveerr);
        return false;
    }
    
    close(fd);
    
    if (atomic) {
        // preserve the mode as passed in originally
        chmod(auxPath, mode);
                
        if (0 != rename(auxPath, cpath)) {
            unlink(auxPath);
            return false;
        }
        
        // If the file was renamed successfully and we wrote it as root we need to reset the owner & group as they were.
        if (writingFileAsRoot) {
            chown(cpath, owner, group);
        }
    }
    return true;
}
Exemplo n.º 17
0
DispValue *DispValue::_update(DispValue *source, 
			      bool& was_changed, bool& was_initialized)
{
    if (source == this)
    {
	// We're updated from ourselves -- ignore it all.  
	// This happens when a cluster is updated from the values of
	// the clustered dislays.
	if (descendant_changed())
	    was_changed = true;

	return this;
    }

    if (changed)
    {
	// Clear `changed' flag
	changed = false;
	was_changed = true;
    }

    if (source->enabled() != enabled())
    {
	myenabled = source->enabled();
	was_changed = true;

	// We don't set CHANGED to true since enabled/disabled changes
	// are merely a change in the view, not a change in the data.
    }

    if (source->full_name() == full_name() && source->type() == type())
    {
	switch (type())
	{
	case Simple:
	case Text:
	case Pointer:
	    // Atomic values
	    if (_value != source->value())
	    {
		_value = source->value();
		changed = was_changed = true;
	    }
	    return this;

	case Array:
	    // Array.  Check for 1st element, too.
	    if (_have_index_base != source->_have_index_base &&
		(_have_index_base && _index_base != source->_index_base))
		break;

	    // FALL THROUGH
	case Reference:
	case Sequence:
	    // Numbered children.  If size changed, we assume
	    // the whole has been changed.
	    if (nchildren() == source->nchildren())
	    {
		for (int i = 0; i < nchildren(); i++)
		{
		    // Update each child
		    _children[i] = child(i)->update(source->child(i),
						    was_changed,
						    was_initialized);
		}
		return this;
	    }
	    break;

	case List:
	case Struct:
	{
	    // Named children.  Check whether names are the same.
	    bool same_members = (nchildren() == source->nchildren());

	    for (int i = 0; same_members && i < nchildren(); i++)
	    {
		if (child(i)->full_name() != source->child(i)->full_name())
		    same_members = false;
	    }

	    if (same_members)
	    {
		// Update each child
		for (int i = 0; i < nchildren(); i++)
		{
		    _children[i] = child(i)->update(source->child(i),
						    was_changed,
						    was_initialized);
		}
		return this;
	    }

	    // Members have changed.
	    // Be sure to mark only those members that actually have changed
	    // (i.e. don't mark the entire struct and don't mark new members)
	    // We do so by creating a new list of children.  `Old' children
	    // that still are reported get updated; `new' children are added.
	    DispValueArray new_children;
	    DispValueArray processed_children;
	    for (int j = 0; j < source->nchildren(); j++)
	    {
		DispValue *c = 0;
		for (int i = 0; c == 0 && i < nchildren(); i++)
		{
		    bool processed = false;
		    for (int k = 0; k < processed_children.size(); k++)
		    {
			if (child(i) == processed_children[k])
			    processed = true;
		    }
		    if (processed)
			continue;

		    if (child(i)->full_name() == source->child(j)->full_name())
		    {
			c = child(i)->update(source->child(j),
					     was_changed,
					     was_initialized);
			processed_children += child(i);
		    }
		}

		if (c == 0)
		{
		    // Child not found -- use source child instead
		    c = source->child(j)->link();
		}

		new_children += c;
	    }
	    _children = new_children;
	    was_changed = was_initialized = true;
	    return this;
	}

	case UnknownType:
	    assert(0);
	    abort();
	}
    }

    // Type, name or structure have changed -- use SOURCE instead of original
    DispValue *ret = source->link();
    ret->changed = was_changed = was_initialized = true;

    // Copy the basic settings
    ret->myexpanded = expanded();
    ret->dereference(dereferenced());
    ret->set_orientation(orientation());
    ret->set_member_names(member_names());

    // Have new DispValue take over the plotter
    if (ret->plotter() == 0)
    {
	ret->_plotter = plotter();
	_plotter = 0;
    }

    unlink();
    return ret;
}
Exemplo n.º 18
0
void aofRemoveTempFile(pid_t childpid) {
    char tmpfile[256];

    snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) childpid);
    unlink(tmpfile);
}
Exemplo n.º 19
0
Arquivo: spawn.c Projeto: ytoto/uemacs
/*
 * Pipe a one line command into a window
 * Bound to ^X @
 */
int pipecmd(int f, int n)
{
	int s;		/* return status from CLI */
	struct window *wp;	/* pointer to new window */
	struct buffer *bp;	/* pointer to buffer to zot */
	char line[NLINE];	/* command line send to shell */
	static char bname[] = "command";

	static char filnam[NSTRING] = "command";

#if     MSDOS
	char *tmp;
	FILE *fp;
	int len;
#endif

	/* don't allow this command if restricted */
	if (restflag)
		return resterr();

#if	MSDOS
	if ((tmp = getenv("TMP")) == NULL
	    && (tmp = getenv("TEMP")) == NULL)
		xstrcpy(filnam, "command");
	else {
		xstrcpy(filnam, tmp);
		len = strlen(tmp);
		if (len <= 0 || filnam[len - 1] != '\\'
		    && filnam[len - 1] != '/')
			strcat(filnam, "\\");
		strcat(filnam, "command");
	}
#endif

#if     VMS
	mlwrite("Not available under VMS");
	return FALSE;
#endif

	/* get the command to pipe in */
	if ((s = mlreply("@", line, NLINE)) != TRUE)
		return s;

	/* get rid of the command output buffer if it exists */
	if ((bp = bfind(bname, FALSE, 0)) != FALSE) {
		/* try to make sure we are off screen */
		wp = wheadp;
		while (wp != NULL) {
			if (wp->w_bufp == bp) {
#if	PKCODE
				if (wp == curwp)
					delwind(FALSE, 1);
				else
					onlywind(FALSE, 1);
				break;
#else
				onlywind(FALSE, 1);
				break;
#endif
			}
			wp = wp->w_wndp;
		}
		if (zotbuf(bp) != TRUE)

			return FALSE;
	}
#if     MSDOS
	strcat(line, " >>");
	strcat(line, filnam);
	movecursor(term.t_nrow, 0);
	TTkclose();
	shellprog(line);
	TTkopen();
	sgarbf = TRUE;
	if ((fp = fopen(filnam, "r")) == NULL) {
		s = FALSE;
	} else {
		fclose(fp);
		s = TRUE;
	}
#endif

#if     V7 | USG | BSD
	TTflush();
	TTclose();		/* stty to old modes    */
	TTkclose();
	strcat(line, ">");
	strcat(line, filnam);
	system(line);
	TTopen();
	TTkopen();
	TTflush();
	sgarbf = TRUE;
	s = TRUE;
#endif

	if (s != TRUE)
		return s;

	/* split the current window to make room for the command output */
	if (splitwind(FALSE, 1) == FALSE)
		return FALSE;

	/* and read the stuff in */
	if (getfile(filnam, FALSE) == FALSE)
		return FALSE;

	/* make this window in VIEW mode, update all mode lines */
	curwp->w_bufp->b_mode |= MDVIEW;
	wp = wheadp;
	while (wp != NULL) {
		wp->w_flag |= WFMODE;
		wp = wp->w_wndp;
	}

	/* and get rid of the temporary file */
	unlink(filnam);
	return TRUE;
}
Exemplo n.º 20
0
/* Write a sequence of commands able to fully rebuild the dataset into
 * "filename". Used both by REWRITEAOF and BGREWRITEAOF.
 *
 * In order to minimize the number of commands needed in the rewritten
 * log Redis uses variadic commands when possible, such as RPUSH, SADD
 * and ZADD. However at max REDIS_AOF_REWRITE_ITEMS_PER_CMD items per time
 * are inserted using a single command. */
int rewriteAppendOnlyFile(char *filename) {
    dictIterator *di = NULL;
    dictEntry *de;
    rio aof;
    FILE *fp;
    char tmpfile[256];
    int j;
    long long now = mstime();

    /* Note that we have to use a different temp name here compared to the
     * one used by rewriteAppendOnlyFileBackground() function. */
    snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) getpid());
    fp = fopen(tmpfile,"w");
    if (!fp) {
        redisLog(REDIS_WARNING, "Opening the temp file for AOF rewrite in rewriteAppendOnlyFile(): %s", strerror(errno));
        return REDIS_ERR;
    }

    rioInitWithFile(&aof,fp);
    if (server.aof_rewrite_incremental_fsync)
        rioSetAutoSync(&aof,REDIS_AOF_AUTOSYNC_BYTES);
    for (j = 0; j < server.dbnum; j++) {
        char selectcmd[] = "*2\r\n$6\r\nSELECT\r\n";
        redisDb *db = server.db+j;
        dict *d = db->dict;
        if (dictSize(d) == 0) continue;
        di = dictGetSafeIterator(d);
        if (!di) {
            fclose(fp);
            return REDIS_ERR;
        }

        /* SELECT the new DB */
        if (rioWrite(&aof,selectcmd,sizeof(selectcmd)-1) == 0) goto werr;
        if (rioWriteBulkLongLong(&aof,j) == 0) goto werr;

        /* Iterate this DB writing every entry */
        while((de = dictNext(di)) != NULL) {
            sds keystr;
            robj key, *o;
            long long expiretime;

            keystr = dictGetKey(de);
            o = dictGetVal(de);
            initStaticStringObject(key,keystr);

            expiretime = getExpire(db,&key);

            /* If this key is already expired skip it */
            if (expiretime != -1 && expiretime < now) continue;

            /* Save the key and associated value */
            if (o->type == REDIS_STRING) {
                /* Emit a SET command */
                char cmd[]="*3\r\n$3\r\nSET\r\n";
                if (rioWrite(&aof,cmd,sizeof(cmd)-1) == 0) goto werr;
                /* Key and value */
                if (rioWriteBulkObject(&aof,&key) == 0) goto werr;
                if (rioWriteBulkObject(&aof,o) == 0) goto werr;
            } else if (o->type == REDIS_LIST) {
                if (rewriteListObject(&aof,&key,o) == 0) goto werr;
            } else if (o->type == REDIS_SET) {
                if (rewriteSetObject(&aof,&key,o) == 0) goto werr;
            } else if (o->type == REDIS_ZSET) {
                if (rewriteSortedSetObject(&aof,&key,o) == 0) goto werr;
            } else if (o->type == REDIS_HASH) {
                if (rewriteHashObject(&aof,&key,o) == 0) goto werr;
            } else {
                redisPanic("Unknown object type");
            }
            /* Save the expire time */
            if (expiretime != -1) {
                char cmd[]="*3\r\n$9\r\nPEXPIREAT\r\n";
                if (rioWrite(&aof,cmd,sizeof(cmd)-1) == 0) goto werr;
                if (rioWriteBulkObject(&aof,&key) == 0) goto werr;
                if (rioWriteBulkLongLong(&aof,expiretime) == 0) goto werr;
            }
        }
        dictReleaseIterator(di);
    }

    /* Make sure data will not remain on the OS's output buffers */
    fflush(fp);
    aof_fsync(fileno(fp));
    fclose(fp);

    /* Use RENAME to make sure the DB file is changed atomically only
     * if the generate DB file is ok. */
    if (rename(tmpfile,filename) == -1) {
        redisLog(REDIS_WARNING,"Error moving temp append only file on the final destination: %s", strerror(errno));
        unlink(tmpfile);
        return REDIS_ERR;
    }
    redisLog(REDIS_NOTICE,"SYNC append only file rewrite performed");
    return REDIS_OK;

werr:
    fclose(fp);
    unlink(tmpfile);
    redisLog(REDIS_WARNING,"Write error writing append only file on disk: %s", strerror(errno));
    if (di) dictReleaseIterator(di);
    return REDIS_ERR;
}
Exemplo n.º 21
0
Arquivo: 2-1.c Projeto: Nan619/ltp-ddt
/* Main entry point. */
int main(int argc, char *argv[])
{
	int ret;
	int sc;
	pthread_mutexattr_t ma;

	testdata_t *td;
	testdata_t alternativ;

	int do_fork;

	pid_t child_pr = 0, chkpid;
	int status;
	pthread_t child_th;

	long pshared, mf;

	/* Initialize output */
	output_init();

	/* Test system abilities */
	pshared = sysconf(_SC_THREAD_PROCESS_SHARED);
	mf = sysconf(_SC_MAPPED_FILES);

#if VERBOSE > 0
	output("Test starting\n");
	output("System abilities:\n");
	output(" TSH : %li\n", pshared);
	output(" MF  : %li\n", mf);
	if ((mf < 0) || (pshared < 0))
		output("Process-shared attributes won't be tested\n");
#endif

/**********
 * Allocate space for the testdata structure
 */
	if (mf < 0) {
		/* Cannot mmap a file (or not interested in this), we use an alternative method */
		td = &alternativ;
		pshared = -1;	/* We won't do this testing anyway */
#if VERBOSE > 0
		output("Testdata allocated in the process memory.\n");
#endif
	} else {
		/* We will place the test data in a mmaped file */
		char filename[] = "/tmp/mutex_trylock_2-1-XXXXXX";
		size_t sz;
		void *mmaped;
		int fd;
		char *tmp;

		/* We now create the temp files */
		fd = mkstemp(filename);
		if (fd == -1) {
			UNRESOLVED(errno,
				   "Temporary file could not be created");
		}

		/* and make sure the file will be deleted when closed */
		unlink(filename);

#if VERBOSE > 1
		output("Temp file created (%s).\n", filename);
#endif

		sz = (size_t) sysconf(_SC_PAGESIZE);

		tmp = calloc(1, sz);
		if (tmp == NULL) {
			UNRESOLVED(errno, "Memory allocation failed");
		}

		/* Write the data to the file.  */
		if (write(fd, tmp, sz) != (ssize_t) sz) {
			UNRESOLVED(sz, "Writting to the file failed");
		}

		free(tmp);

		/* Now we can map the file in memory */
		mmaped =
		    mmap(NULL, sz, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
		if (mmaped == MAP_FAILED) {
			UNRESOLVED(errno, "mmap failed");
		}

		td = (testdata_t *) mmaped;

		/* Our datatest structure is now in shared memory */
#if VERBOSE > 1
		output("Testdata allocated in shared memory.\n");
#endif
	}

/**********
 * For each test scenario, initialize the attributes and other variables.
 * Do the whole thing for each time to test.
 */
	for (sc = 0; sc < NSCENAR; sc++) {
#if VERBOSE > 1
		output("[parent] Preparing attributes for: %s\n",
		       scenarii[sc].descr);
#endif
		/* set / reset everything */
		do_fork = 0;
		ret = pthread_mutexattr_init(&ma);
		if (ret != 0) {
			UNRESOLVED(ret,
				   "[parent] Unable to initialize the mutex attribute object");
		}

		/* Set the mutex type */
		ret = pthread_mutexattr_settype(&ma, scenarii[sc].m_type);
		if (ret != 0) {
			UNRESOLVED(ret, "[parent] Unable to set mutex type");
		}
#if VERBOSE > 1
		output("[parent] Mutex type : %i\n", scenarii[sc].m_type);
#endif

		/* Set the pshared attributes, if supported */
		if ((pshared > 0) && (scenarii[sc].m_pshared != 0)) {
			ret =
			    pthread_mutexattr_setpshared(&ma,
							 PTHREAD_PROCESS_SHARED);
			if (ret != 0) {
				UNRESOLVED(ret,
					   "[parent] Unable to set the mutex process-shared");
			}
#if VERBOSE > 1
			output("[parent] Mutex is process-shared\n");
#endif
		}
#if VERBOSE > 1
		else {
			output("[parent] Mutex is process-private\n");
		}
#endif

		/* Tell whether the test will be across processes */
		if ((pshared > 0) && (scenarii[sc].fork != 0)) {
			do_fork = 1;
#if VERBOSE > 1
			output("[parent] Child will be a new process\n");
#endif
		}
#if VERBOSE > 1
		else {
			output("[parent] Child will be a new thread\n");
		}
#endif

/**********
 * Initialize the testdata_t structure with the previously defined attributes
 */
		/* Initialize the mutex */
		ret = pthread_mutex_init(&(td->mtx), &ma);
		if (ret != 0) {
			UNRESOLVED(ret, "[parent] Mutex init failed");
		}

		/* Initialize the other datas from the test structure */
		td->status = 0;

/**********
 * Proceed to the actual testing
 */
		/* Trylock the mutex twice before creating children */
		ret = pthread_mutex_trylock(&(td->mtx));
		if (ret != 0) {
			UNRESOLVED(ret, "[parent] Unable to trylock the mutex");
		}
		ret = pthread_mutex_trylock(&(td->mtx));

		if (scenarii[sc].m_type == PTHREAD_MUTEX_RECURSIVE) {
			if (ret != 0) {
				FAILED
				    ("Failed to pthread_mutex_trylock() twice a recursive mutex");
			}

			/* Unlock once so the count is "1" */
			ret = pthread_mutex_unlock(&(td->mtx));
			if (ret != 0) {
				UNRESOLVED(ret, "Failed to unlock the mutex");
			}
		} else if (ret == 0) {
			UNRESOLVED(-1,
				   "Main was able to pthread_mutex_trylock() twice without error");
		}

		/* Create the children */
		if (do_fork != 0) {
			/* We are testing across processes */
			child_pr = fork();
			if (child_pr == -1) {
				UNRESOLVED(errno, "[parent] Fork failed");
			}

			if (child_pr == 0) {
#if VERBOSE > 3
				output
				    ("[child] Child process is starting...\n");
#endif

				if (tf((void *)td) != NULL) {
					UNRESOLVED(-1,
						   "[child] Got an unexpected return value from test function");
				} else {
					/* We cannot use the PASSED macro here since it would terminate the output */
					exit(0);
				}
			}
			/* Only the parent process goes further */
		} else {	/* do_fork == 0 */

			/* We are testing across two threads */
			ret = pthread_create(&child_th, NULL, tf, td);
			if (ret != 0) {
				UNRESOLVED(ret,
					   "[parent] Unable to create the child thread.");
			}
		}

		/* Wait for the child to terminate */
		if (do_fork != 0) {
			/* We were testing across processes */
			ret = 0;
			chkpid = waitpid(child_pr, &status, 0);
			if (chkpid != child_pr) {
				output("Expected pid: %i. Got %i\n",
				       (int)child_pr, (int)chkpid);
				UNRESOLVED(errno, "Waitpid failed");
			}
			if (WIFSIGNALED(status)) {
				output("Child process killed with signal %d\n",
				       WTERMSIG(status));
				UNRESOLVED(-1, "Child process was killed");
			}

			if (WIFEXITED(status)) {
				ret = WEXITSTATUS(status);
			} else {
				UNRESOLVED(-1,
					   "Child process was neither killed nor exited");
			}

			if (ret != 0) {
				exit(ret);	/* Output has already been closed in child */
			}

		} else {	/* child was a thread */

			ret = pthread_join(child_th, NULL);
			if (ret != 0) {
				UNRESOLVED(ret,
					   "[parent] Unable to join the thread");
			}
		}

		/* Check the child status */
		if (td->status != EBUSY) {
			output("Unexpected return value: %d (%s)\n", td->status,
			       strerror(td->status));
			FAILED
			    ("pthread_mutex_trylock() did not return EBUSY in the child");
		}

		/* Unlock the mutex */
		ret = pthread_mutex_unlock(&(td->mtx));
		if (ret != 0) {
			FAILED
			    ("Failed to unlock the mutex -- count is broken?");
		}

		ret = pthread_mutex_unlock(&(td->mtx));
		if (ret == 0) {
			FAILED
			    ("Was able to unlock once more the mutex -- count is broken?");
		}

/**********
 * Destroy the data
 */
		ret = pthread_mutex_destroy(&(td->mtx));
		if (ret != 0) {
			UNRESOLVED(ret, "Failed to destroy the mutex");
		}

		ret = pthread_mutexattr_destroy(&ma);
		if (ret != 0) {
			UNRESOLVED(ret,
				   "Failed to destroy the mutex attribute object");
		}

	}			/* Proceed to the next scenario */

#if VERBOSE > 0
	output("Test passed\n");
#endif

	PASSED;
}
int
delegate_to_matlab( Dbptr db, Pf *delegate_pf )
{
	char	scriptfile[FILENAME_MAX];
	char	fifofile[FILENAME_MAX];
	char	pffile[FILENAME_MAX];
	char	cmd[STRSZ];
	char	*commands;
	char	*mypath;
	char	*cwd;
	FILE	*fp;
	Tbl	*keys;
	char	*key;
	Pf	*pfpart;
	pid_t	pid;
	int	status;
	int	i;

	if( ( mypath = datafile( "PATH", "matlab" ) ) == 0 ) {

		elog_complain( 0, "Couldn't find matlab on path.\n" );

		return -1;

	} else if( access( mypath, R_OK|X_OK ) ) {

		elog_complain( 0, "Couldn't find matlab on path.\n" );
		
		return -1;
	}

	if( ( commands = pfget_string( delegate_pf, "commands" ) ) == NULL ) {

		elog_complain( 0, "No commands &Literal in parameter file\n" );

		return -1;
	}

	cwd = getcwd( NULL, FILENAME_MAX );

	sprintf( scriptfile, "/tmp/dbgme_script_%d_%d.m", getuid(), getpid() );
	sprintf( fifofile, "/tmp/dbgme_fifo_%d_%d", getuid(), getpid() );
	sprintf( pffile, "/tmp/dbgme_pf_%d_%d.pf", getuid(), getpid() );

	mkfifo( fifofile, 0775 );

	fp = fopen( pffile, "w" ); 
	keys = pfkeys( delegate_pf );
	for( i = 0; i < maxtbl( keys ); i++ ) {

		key = gettbl( keys, i );

		if( ! strcmp( key, "commands" ) ) {

			continue;
		}

		pfresolve( delegate_pf, key, 0, &pfpart );

		fprintf( fp, "%s ", key );
		pfout( fp, pfpart ); 
	}
	fclose( fp ); 
	
	fp = fopen( scriptfile, "w" );
	fprintf( fp, "addpath('%s')\n", cwd );
	fprintf( fp, "db = dbread_view( '%s' );\n", fifofile );
	fprintf( fp, "pf = dbpf( '%s' );\n", pffile );
	fprintf( fp, "%s\n", commands );
	fprintf( fp, "exit\n" );
	fclose( fp );

	sprintf( cmd, 
		"try, "
			"run %s, "
		"catch, "
			"lasterr, "
			"elog_clear_register('print'), "
			"unix(['kill -9 ' num2str(getpid)]), "
		"end", 
		scriptfile );

	if( ( pid = fork() ) == 0 ) {

		if( Verbose ) {

			fprintf( stderr, "Running Matlab delegate\n" );

		} else {

			fflush( stderr );
			fclose( stdout );
		}

		execlp( "matlab", "matlab", "-nodisplay", "-nojvm",
			"-r", cmd, NULL );

	} else {

		fp = fopen( fifofile, "w" );
		dbwrite_view( db, fp );
		fclose( fp );

		wait( &status );
	}

	if( Verbose ) {

		fprintf( stderr, "Matlab exit status is %d\n", status );
	}

	free( cwd );

	unlink( scriptfile );
	unlink( fifofile );
	unlink( pffile );

	if( status != 0 ) {

		return -1;

	} else {

		return 0;
	}
}
Exemplo n.º 23
0
int main( int argc, char *argv[] )
{
  char out_filename[256];
  
  if( argc != 4 )
  {
    fprintf( stderr, "closeshp poly_shape arc_shape output_shape\n" );
    return 1;
  }
  char *poly_file = argv[1];
  char *arc_file = argv[2];
  char *out_file = argv[3];

  struct source poly, arc, simplified;
  memset( &poly, 0, sizeof(poly) );
  memset( &arc, 0, sizeof(arc) );
  memset( &simplified, 0, sizeof(simplified) );
  poly.in_memory = arc.in_memory = 0;
  simplified.in_memory = 1;

  /* open shapefiles and dbf files */
  if( SourceOpen( &poly, poly_file, SHPT_POLYGON ) )
    return 1;
  if( SourceOpen( &arc, arc_file, SHPT_ARC ) )
    return 1;

  sprintf( out_filename, "%s_p", out_file );
  shp_out = SHPCreate( out_filename, SHPT_POLYGON );
  if( !shp_out )
  {
    fprintf( stderr, "Couldn't create shapefile '%s': %s\n", out_file, strerror(errno));
    return 1;
  }
  
  dbf_out = DBFCreate( out_filename );
  if( !dbf_out )
  {
    fprintf( stderr, "Couldn't create DBF '%s': %s\n", out_file, strerror(errno));
    return 1;
  }
//  DBFAddField( dbf_out, "way_id", FTInteger, 11, 0 );
//  DBFAddField( dbf_out, "orientation", FTInteger, 1, 0 );
  DBFAddField( dbf_out, "error", FTInteger, 1, 0 );
  DBFAddField( dbf_out, "tile_x", FTInteger, 4, 0 );
  DBFAddField( dbf_out, "tile_y", FTInteger, 4, 0 );

  /* Initialise node arrays */
  v_x = malloc( MAX_NODES * sizeof(double) );
  v_y = malloc( MAX_NODES * sizeof(double) );
  
  if( !v_x || !v_y )
  {
    fprintf( stderr, "Couldn't allocate memory for nodes\n" );
    return 1;
  }
  /* Setup state */
  struct state state;
  memset( &state, 0, sizeof(state) );
  ResizeSubareas(&state, INIT_MAX_SUBAREAS);
  
  // Temporary file for simplified shapes
  {
      // Make the file and open it
      char filename[32];
      sprintf( filename, "tmp_coastline_%d", getpid() );
      simplified.shp = SHPCreate( filename, SHPT_ARC );
      if( !simplified.shp )
      {
          fprintf( stderr, "Couldn't open temporary shapefile: %s\n", strerror(errno) );
          return 1;
      }
      // And now unlink them so they're cleaned up when we die
      int len = strlen( filename );
      strcpy( filename+len, ".shp" );
      unlink(filename);
      strcpy( filename+len, ".shx" );
      unlink(filename);
      
      // Setup the bitmap while creating the simplified polygons
      InitBitmap( &arc, &simplified );
      InitBitmap( &poly, &simplified );
      
      // And index the simplified polygons
      simplified.shx = SHPCreateTree( simplified.shp, 2, 10, NULL, NULL );
      if( !simplified.shx )
      {
          fprintf( stderr, "Couldn't build temporary shapetree\n" );
          return 1;
      }
      SHPGetInfo( simplified.shp, &simplified.shape_count, NULL, NULL, NULL );
      simplified.shapes = calloc( simplified.shape_count, sizeof(SHPObject*) );
  }
  /* Split coastlines into arcs no longer than MAX_NODES_PER_ARC long */
  sprintf( out_filename, "%s_i", out_file );
  SplitCoastlines( &poly, &arc, out_filename );

#if !TEST  
  for( int i=0; i<DIVISIONS; i++ )
    for( int j=0; j<DIVISIONS; j++ )  //Divide the world into mercator blocks approx 100km x 100km
#else
  for( int i=204; i<=204; i++ )
    for( int j=248; j<=248; j++ )  //Divide the world into mercator blocks approx 100km x 100km
#endif
    {
      state.x = i;
      state.y = j;
      
      double left   = -MERC_MAX + (i*MERC_BLOCK) - TILE_OVERLAP;
      double right  = -MERC_MAX + ((i+1)*MERC_BLOCK) + TILE_OVERLAP;
      double bottom = -MERC_MAX + (j*MERC_BLOCK) - TILE_OVERLAP;
      double top    = -MERC_MAX + ((j+1)*MERC_BLOCK) + TILE_OVERLAP;
      
      if( left  < -MERC_MAX ) left  = -MERC_MAX;
      if( right > +MERC_MAX ) right = +MERC_MAX;
      
      state.lb[0] = left;
      state.lb[1] = bottom;
      state.rt[0] = right;
      state.rt[1] = top;
      
      if(isatty(STDERR_FILENO))
//        fprintf( stderr, "\rProcessing (%d,%d)  (%.2f,%.2f)-(%.2f,%.2f)   ", i, j, left, bottom, right, top );
        fprintf( stderr, "\rProcessing (%d,%d)  (%.2f,%.2f)-(%.2f,%.2f)   ", i, j, state.lb[0], state.lb[1], state.rt[0], state.rt[1] );
      state.seg_count = 0;
      state.subarea_count = 0;
      state.subarea_nodecount = 0;
      state.enclosed = 0;
      
      // Optimisation: if we have determined nothing enters the tile, we can used the simplified tiles
      // Basically, we only need to test for enclosure
      if( check_tile( state.x, state.y ) )
      {
        Process( &state, &poly, 1 );
        Process( &state, &arc,  0 );
      }
      else
        Process( &state, &simplified, 0 );

      OutputSegs( &state );
    }
    
  free( state.sub_areas );
  free( simplified.shapes );
  SHPDestroyTree( poly.shx );
  SHPDestroyTree( arc.shx );
  SHPDestroyTree( simplified.shx );
  DBFClose( poly.dbf );
  DBFClose( arc.dbf );
  DBFClose( dbf_out );
  SHPClose( poly.shp );
  SHPClose( arc.shp );
  SHPClose( simplified.shp );
  SHPClose( shp_out );
  
  printf("\n");
  return 0;
}
Exemplo n.º 24
0
static void stat_update_cb(EV_P_ ev_timer *watcher, int revents)
{
    struct sockaddr_un svaddr, claddr;
    int sfd = -1;
    size_t msgLen;
    char resp[BUF_SIZE];

    if (verbose) {
        LOGI("update traffic stat: tx: %"PRIu64" rx: %"PRIu64"", tx, rx);
    }

    snprintf(resp, BUF_SIZE, "stat: {\"%s\":%"PRIu64"}", server_port, tx + rx);
    msgLen = strlen(resp) + 1;

    ss_addr_t ip_addr = { .host = NULL, .port = NULL };
    parse_addr(manager_address, &ip_addr);

    if (ip_addr.host == NULL || ip_addr.port == NULL) {
        sfd = socket(AF_UNIX, SOCK_DGRAM, 0);
        if (sfd == -1) {
            ERROR("stat_socket");
            return;
        }

        memset(&claddr, 0, sizeof(struct sockaddr_un));
        claddr.sun_family = AF_UNIX;
        snprintf(claddr.sun_path, sizeof(claddr.sun_path), "/tmp/shadowsocks.%s", server_port);

        unlink(claddr.sun_path);

        if (bind(sfd, (struct sockaddr *) &claddr, sizeof(struct sockaddr_un)) == -1) {
            ERROR("stat_bind");
            close(sfd);
            return;
        }

        memset(&svaddr, 0, sizeof(struct sockaddr_un));
        svaddr.sun_family = AF_UNIX;
        strncpy(svaddr.sun_path, manager_address, sizeof(svaddr.sun_path) - 1);

        if (sendto(sfd, resp, strlen(resp) + 1, 0, (struct sockaddr *) &svaddr,
                    sizeof(struct sockaddr_un)) != msgLen) {
            ERROR("stat_sendto");
            close(sfd);
            return;
        }

        unlink(claddr.sun_path);

    } else {
        struct sockaddr_storage storage;
        memset(&storage, 0, sizeof(struct sockaddr_storage));
        if (get_sockaddr(ip_addr.host, ip_addr.port, &storage, 0) == -1) {
            ERROR("failed to parse the manager addr");
            return;
        }

        sfd = socket(storage.ss_family, SOCK_DGRAM, 0);

        if (sfd == -1) {
            ERROR("stat_socket");
            return;
        }

        size_t addr_len = get_sockaddr_len((struct sockaddr *)&storage);
        if (sendto(sfd, resp, strlen(resp) + 1, 0, (struct sockaddr *)&storage,
                    addr_len) != msgLen) {
            ERROR("stat_sendto");
            close(sfd);
            return;
        }
    }

    close(sfd);
}
Exemplo n.º 25
0
static int tcl_rmdir(ClientData cd, Tcl_Interp *irp,
                     int argc, char *argv[])
{
  FILE *fdb;
  filedb_entry *fdbe;
  char *s = NULL, *t, *d, *p;

  BADARGS(2, 2, " dir");

  malloc_strcpy(s, argv[1]);
  if (s[strlen(s) - 1] == '/')
    s[strlen(s) - 1] = 0;
  p = strrchr(s, '/');
  if (p == NULL) {
    p = s;
    d = "";
  } else {
    *p = 0;
    p++;
    d = s;
  }

  fdb = filedb_open(d, 0);
  if (!fdb) {
    Tcl_AppendResult(irp, "1", NULL);
    my_free(s);
    return TCL_OK;
  }
  filedb_readtop(fdb, NULL);
  fdbe = filedb_matchfile(fdb, ftell(fdb), p);

  if (!fdbe) {
    Tcl_AppendResult(irp, "1", NULL);
    filedb_close(fdb);
    my_free(s);
    return TCL_OK;
  }
  if (!(fdbe->stat & FILE_DIR)) {
    Tcl_AppendResult(irp, "1", NULL);
    filedb_close(fdb);
    free_fdbe(&fdbe);
    my_free(s);
    return TCL_OK;
  }
  /* Erase '.filedb' and '.files' if they exist */
  t = nmalloc(strlen(dccdir) + strlen(d) + strlen(p) + 11);
  sprintf(t, "%s%s/%s/.filedb", dccdir, d, p);
  unlink(t);
  sprintf(t, "%s%s/%s/.files", dccdir, d, p);
  unlink(t);
  sprintf(t, "%s%s/%s", dccdir, d, p);
  my_free(s);
  if (rmdir(t) == 0) {
    filedb_delfile(fdb, fdbe->pos);
    filedb_close(fdb);
    free_fdbe(&fdbe);
    my_free(t);
    Tcl_AppendResult(irp, "0", NULL);
    return TCL_OK;
  }
  my_free(t);
  free_fdbe(&fdbe);
  filedb_close(fdb);
  Tcl_AppendResult(irp, "1", NULL);
  return TCL_OK;
}
Exemplo n.º 26
0
int main(int ac, char *av[])
{
	int pid, child, status, count, k, j;
	char name[3];

	int lc;
	const char *msg;

	/*
	 * parse standard options
	 */
	if ((msg = parse_opts(ac, av, NULL, NULL)) != NULL)
		tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg);

	/*
	 * Default values for run conditions.
	 */
	iterations = 50;
	nchild = 5;

	if (signal(SIGTERM, term) == SIG_ERR) {
		tst_resm(TBROK, "first signal failed");

	}

	/* use the default values for run conditions */
	for (lc = 0; TEST_LOOPING(lc); lc++) {

		local_flag = PASSED;
		/*
		 * Make a directory to do this in; ignore error if already exists.
		 */
		parent_pid = getpid();
		tst_tmpdir();

		if (!startdir[0]) {
			if (getcwd(startdir, MAXPATHLEN) == NULL) {
				tst_brkm(TFAIL | TERRNO, NULL, "getcwd failed");
			}
		}
		cwd = startdir;

		snprintf(dirname, ARRAY_SIZE(dirname),
			 "%s/ftest06.%d", cwd, getpid());
		snprintf(homedir, ARRAY_SIZE(homedir),
			 "%s/ftest06h.%d", cwd, getpid());

		mkdir(dirname, 0755);
		mkdir(homedir, 0755);

		if (chdir(dirname) < 0)
			tst_brkm(TFAIL | TERRNO, cleanup, "\tCan't chdir(%s)",
				 dirname);

		dirlen = strlen(dirname);

		if (chdir(homedir) < 0)
			tst_brkm(TFAIL | TERRNO, cleanup, "\tCan't chdir(%s)",
				 homedir);

		/* enter block */
		for (k = 0; k < nchild; k++) {
			if ((child = fork()) == 0) {
				dotest(k, iterations);
				tst_exit();
			}
			if (child < 0) {
				tst_brkm(TBROK | TERRNO, cleanup,
					 "fork failed");
			}
			pidlist[k] = child;
		}

		/*
		 * Wait for children to finish.
		 */
		count = 0;
		while ((child = wait(&status)) > 0) {
			//tst_resm(TINFO,"Test{%d} exited status = 0x%x", child, status);
			//fprintf(stdout, "status is %d",status);
			if (status) {
				tst_resm(TFAIL,
					 "Test{%d} failed, expected 0 exit.",
					 child);
				local_flag = FAILED;
			}
			++count;
		}

		/*
		 * Should have collected all children.
		 */
		if (count != nchild) {
			tst_resm(TFAIL,
				 "Wrong # children waited on, count = %d",
				 count);
			local_flag = FAILED;
		}

		if (local_flag == PASSED)
			tst_resm(TPASS, "Test passed.");
		else
			tst_resm(TFAIL, "Test failed.");

		if (iterations > 26)
			iterations = 26;

		for (k = 0; k < nchild; k++)
			for (j = 0; j < iterations + 1; j++) {
				ft_mkname(name, dirname, k, j);
				rmdir(name);
				unlink(name);
			}

		if (chdir(startdir) < 0)
			tst_brkm(TFAIL | TERRNO, cleanup, "Can't chdir(%s)",
				 startdir);

		pid = fork();
		if (pid < 0) {
			tst_brkm(TBROK | TERRNO, NULL, "fork failed");
		}

		if (pid == 0) {
			execl("/bin/rm", "rm", "-rf", homedir, NULL);

		} else
			wait(&status);

		if (status)
			tst_resm(TINFO,
				 "CAUTION - ftest06, '%s' may not have been removed.",
				 homedir);

		pid = fork();
		if (pid < 0) {
			tst_brkm(TBROK | TERRNO, NULL, "fork failed");
		}
		if (pid == 0) {
			execl("/bin/rm", "rm", "-rf", dirname, NULL);
			exit(1);
		} else
			wait(&status);
		if (status) {
			tst_resm(TWARN,
				 "CAUTION - ftest06, '%s' may not have been removed.",
				 dirname);
		}

		sync();

	}

	if (local_flag == FAILED)
		tst_resm(TFAIL, "Test failed.");
	else
		tst_resm(TPASS, "Test passed.");

	cleanup();
	tst_exit();
}
Exemplo n.º 27
0
static Port *
OpenPortInternal(const DeviceConfig &config, DataHandler &handler)
{
  const TCHAR *path = NULL;
  TCHAR buffer[MAX_PATH];

  switch (config.port_type) {
  case DeviceConfig::PortType::DISABLED:
    return NULL;

  case DeviceConfig::PortType::SERIAL:
    if (config.path.empty())
      return NULL;

    path = config.path.c_str();
    break;

  case DeviceConfig::PortType::RFCOMM:
#ifdef ANDROID
    if (config.bluetooth_mac.empty()) {
      LogFormat("No Bluetooth MAC configured");
      return NULL;
    }

    return OpenAndroidBluetoothPort(config.bluetooth_mac, handler);
#else
    LogFormat("Bluetooth not available on this platform");
    return NULL;
#endif

  case DeviceConfig::PortType::RFCOMM_SERVER:
#ifdef ANDROID
    return OpenAndroidBluetoothServerPort(handler);
#else
    LogFormat("Bluetooth not available on this platform");
    return NULL;
#endif

  case DeviceConfig::PortType::IOIOUART:
#if defined(ANDROID) && defined(IOIOLIB)
    if (config.ioio_uart_id >= AndroidIOIOUartPort::getNumberUarts()) {
      LogFormat("No IOIOUart configured in profile");
      return NULL;
    }

    return OpenAndroidIOIOUartPort(config.ioio_uart_id, config.baud_rate,
                                   handler);
#else
    LogFormat("IOIO Uart not available on this platform or version");
    return NULL;
#endif

  case DeviceConfig::PortType::AUTO:
    if (!DetectGPS(buffer, sizeof(buffer))) {
      LogFormat("no GPS detected");
      return NULL;
    }

    LogStartUp(_T("GPS detected: %s"), buffer);

    path = buffer;
    break;

  case DeviceConfig::PortType::INTERNAL:
  case DeviceConfig::PortType::DROIDSOAR_V2:
  case DeviceConfig::PortType::NUNCHUCK:
  case DeviceConfig::PortType::I2CPRESSURESENSOR:
  case DeviceConfig::PortType::IOIOVOLTAGE:
    break;

  case DeviceConfig::PortType::TCP_LISTENER: {
    TCPPort *port = new TCPPort(handler);
    if (!port->Open(config.tcp_port)) {
      delete port;
      return NULL;
    }

    return port;
  }

  case DeviceConfig::PortType::UDP_LISTENER: {
    SocketPort *port = new SocketPort(handler);
    if (!port->OpenUDPListener(config.tcp_port)) {
      delete port;
      return NULL;
    }

    return port;
  }

  case DeviceConfig::PortType::PTY: {
#if defined(HAVE_POSIX) && !defined(ANDROID)
    if (config.path.empty())
      return NULL;

    if (unlink(config.path.c_str()) < 0 && errno != ENOENT)
      return NULL;

    TTYPort *port = new TTYPort(handler);
    const char *slave_path = port->OpenPseudo();
    if (slave_path == NULL) {
      delete port;
      return NULL;
    }

    if (symlink(slave_path, config.path.c_str()) < 0) {
      delete port;
      return NULL;
    }

    return port;
#else
    return NULL;
#endif
  }
  }

  if (path == NULL)
    return NULL;

#ifdef HAVE_POSIX
  TTYPort *port = new TTYPort(handler);
#else
  SerialPort *port = new SerialPort(handler);
#endif
  if (!port->Open(path, config.baud_rate)) {
    delete port;
    return NULL;
  }

  return port;
}
Exemplo n.º 28
0
static pngquant_error write_image(png8_image *output_image, png24_image *output_image24, const char *outname, struct pngquant_options *options)
{
    FILE *outfile;
    char *tempname = NULL;

    if (options->using_stdout) {
        set_binary_mode(stdout);
        outfile = stdout;

        if (output_image) {
            verbose_printf(options, "  writing %d-color image to stdout", output_image->num_palette);
        } else {
            verbose_printf(options, "  writing truecolor image to stdout");
        }
    } else {
        tempname = temp_filename(outname);
        if (!tempname) return OUT_OF_MEMORY_ERROR;

        if ((outfile = fopen(tempname, "wb")) == NULL) {
            fprintf(stderr, "  error: cannot open '%s' for writing\n", tempname);
            free(tempname);
            return CANT_WRITE_ERROR;
        }

        if (output_image) {
            verbose_printf(options, "  writing %d-color image as %s", output_image->num_palette, filename_part(outname));
        } else {
            verbose_printf(options, "  writing truecolor image as %s", filename_part(outname));
        }
    }

    pngquant_error retval;
    #pragma omp critical (libpng)
    {
        if (output_image) {
            retval = rwpng_write_image8(outfile, output_image);
        } else {
            retval = rwpng_write_image24(outfile, output_image24);
        }
    }

    if (!options->using_stdout) {
        fclose(outfile);

        if (SUCCESS == retval) {
            // Image has been written to a temporary file and then moved over destination.
            // This makes replacement atomic and avoids damaging destination file on write error.
            if (!replace_file(tempname, outname, options->force)) {
                retval = CANT_WRITE_ERROR;
            }
        }

        if (retval) {
            unlink(tempname);
        }
        free(tempname);
    }

    if (retval && retval != TOO_LARGE_FILE) {
        fprintf(stderr, "  error: failed writing image to %s\n", outname);
    }

    return retval;
}
Exemplo n.º 29
0
static int
task_main(int argc, char *argv[])
{
	work_q_item_t *work;

	/* inform about start */
	warnx("Initializing..");

	/* Initialize global variables */
	g_key_offsets[0] = 0;

	for (unsigned i = 0; i < (DM_KEY_NUM_KEYS - 1); i++)
		g_key_offsets[i + 1] = g_key_offsets[i] + (g_per_item_max_index[i] * k_sector_size);

	unsigned max_offset = g_key_offsets[DM_KEY_NUM_KEYS - 1] + (g_per_item_max_index[DM_KEY_NUM_KEYS - 1] * k_sector_size);

	for (unsigned i = 0; i < dm_number_of_funcs; i++)
		g_func_counts[i] = 0;

	/* Initialize the item type locks, for now only DM_KEY_MISSION_STATE supports locking */
	sem_init(&g_sys_state_mutex, 1, 1); /* Initially unlocked */
	for (unsigned i = 0; i < DM_KEY_NUM_KEYS; i++)
		g_item_locks[i] = NULL;
	g_item_locks[DM_KEY_MISSION_STATE] = &g_sys_state_mutex;

	g_task_should_exit = false;

	init_q(&g_work_q);
	init_q(&g_free_q);

	sem_init(&g_work_queued_sema, 1, 0);

	/* See if the data manage file exists and is a multiple of the sector size */
	g_task_fd = open(k_data_manager_device_path, O_RDONLY | O_BINARY);
	if (g_task_fd >= 0) {
		/* File exists, check its size */
		int file_size = lseek(g_task_fd, 0, SEEK_END);
		if ((file_size % k_sector_size) != 0) {
			warnx("Incompatible data manager file %s, resetting it", k_data_manager_device_path);
			close(g_task_fd);
			unlink(k_data_manager_device_path);
		}
		else
			close(g_task_fd);
	}

	/* Open or create the data manager file */
	g_task_fd = open(k_data_manager_device_path, O_RDWR | O_CREAT | O_BINARY);

	if (g_task_fd < 0) {
		warnx("Could not open data manager file %s", k_data_manager_device_path);
		sem_post(&g_init_sema); /* Don't want to hang startup */
		return -1;
	}

	if ((unsigned)lseek(g_task_fd, max_offset, SEEK_SET) != max_offset) {
		close(g_task_fd);
		warnx("Could not seek data manager file %s", k_data_manager_device_path);
		sem_post(&g_init_sema); /* Don't want to hang startup */
		return -1;
	}

	fsync(g_task_fd);

	/* see if we need to erase any items based on restart type */
	int sys_restart_val;
	if (param_get(param_find("SYS_RESTART_TYPE"), &sys_restart_val) == OK) {
		if (sys_restart_val == DM_INIT_REASON_POWER_ON) {
			warnx("Power on restart");
			_restart(DM_INIT_REASON_POWER_ON);
		}
		else if (sys_restart_val == DM_INIT_REASON_IN_FLIGHT) {
			warnx("In flight restart");
			_restart(DM_INIT_REASON_IN_FLIGHT);
		}
		else
			warnx("Unknown restart");
	}
	else
		warnx("Unknown restart");

	/* We use two file descriptors, one for the caller context and one for the worker thread */
	/* They are actually the same but we need to some way to reject caller request while the */
	/* worker thread is shutting down but still processing requests */
	g_fd = g_task_fd;

	warnx("Initialized, data manager file '%s' size is %d bytes", k_data_manager_device_path, max_offset);

	/* Tell startup that the worker thread has completed its initialization */
	sem_post(&g_init_sema);

	/* Start the endless loop, waiting for then processing work requests */
	while (true) {

		/* do we need to exit ??? */
		if ((g_task_should_exit) && (g_fd >= 0)) {
			/* Close the file handle to stop further queuing */
			g_fd = -1;
		}

		if (!g_task_should_exit) {
			/* wait for work */
			sem_wait(&g_work_queued_sema);
		}

		/* Empty the work queue */
		while ((work = dequeue_work_item())) {

			/* handle each work item with the appropriate handler */
			switch (work->func) {
			case dm_write_func:
				g_func_counts[dm_write_func]++;
				work->result =
					_write(work->write_params.item, work->write_params.index, work->write_params.persistence, work->write_params.buf, work->write_params.count);
				break;

			case dm_read_func:
				g_func_counts[dm_read_func]++;
				work->result =
					_read(work->read_params.item, work->read_params.index, work->read_params.buf, work->read_params.count);
				break;

			case dm_clear_func:
				g_func_counts[dm_clear_func]++;
				work->result = _clear(work->clear_params.item);
				break;

			case dm_restart_func:
				g_func_counts[dm_restart_func]++;
				work->result = _restart(work->restart_params.reason);
				break;

			default: /* should never happen */
				work->result = -1;
				break;
			}

			/* Inform the caller that work is done */
			sem_post(&work->wait_sem);
		}

		/* time to go???? */
		if ((g_task_should_exit) && (g_fd < 0))
			break;
	}

	close(g_task_fd);
	g_task_fd = -1;

	/* The work queue is now empty, empty the free queue */
	for (;;) {
		if ((work = (work_q_item_t *)sq_remfirst(&(g_free_q.q))) == NULL)
			break;
		if (work->first)
			free(work);
	}

	destroy_q(&g_work_q);
	destroy_q(&g_free_q);
	sem_destroy(&g_work_queued_sema);
	sem_destroy(&g_sys_state_mutex);

	return 0;
}
Exemplo n.º 30
0
/**
 * fit_handle_file - main FIT file processing function
 *
 * fit_handle_file() runs dtc to convert .its to .itb, includes
 * binary data, updates timestamp property and calculates hashes.
 *
 * datafile  - .its file
 * imagefile - .itb file
 *
 * returns:
 *     only on success, otherwise calls exit (EXIT_FAILURE);
 */
static int fit_handle_file(struct image_tool_params *params)
{
	char tmpfile[MKIMAGE_MAX_TMPFILE_LEN];
	char cmd[MKIMAGE_MAX_DTC_CMDLINE_LEN];
	int tfd, destfd = 0;
	void *dest_blob = NULL;
	struct stat sbuf;
	void *ptr;
	off_t destfd_size = 0;

	/* Flattened Image Tree (FIT) format  handling */
	debug ("FIT format handling\n");

	/* call dtc to include binary properties into the tmp file */
	if (strlen (params->imagefile) +
		strlen (MKIMAGE_TMPFILE_SUFFIX) + 1 > sizeof (tmpfile)) {
		fprintf (stderr, "%s: Image file name (%s) too long, "
				"can't create tmpfile",
				params->imagefile, params->cmdname);
		return (EXIT_FAILURE);
	}
	sprintf (tmpfile, "%s%s", params->imagefile, MKIMAGE_TMPFILE_SUFFIX);

	/* We either compile the source file, or use the existing FIT image */
	if (params->datafile) {
		/* dtc -I dts -O dtb -p 500 datafile > tmpfile */
		snprintf(cmd, sizeof(cmd), "%s %s %s > %s",
			 MKIMAGE_DTC, params->dtc, params->datafile, tmpfile);
		debug("Trying to execute \"%s\"\n", cmd);
	} else {
		snprintf(cmd, sizeof(cmd), "cp %s %s",
			 params->imagefile, tmpfile);
	}
	if (system (cmd) == -1) {
		fprintf (stderr, "%s: system(%s) failed: %s\n",
				params->cmdname, cmd, strerror(errno));
		goto err_system;
	}

	if (params->keydest) {
		destfd = mmap_fdt(params->cmdname, params->keydest,
				  &dest_blob, &sbuf, 1);
		if (destfd < 0)
			goto err_keydest;
		destfd_size = sbuf.st_size;
	}

	tfd = mmap_fdt(params->cmdname, tmpfile, &ptr, &sbuf, 1);
	if (tfd < 0)
		goto err_mmap;

	/* set hashes for images in the blob */
	if (fit_add_verification_data(params->keydir,
				      dest_blob, ptr, params->comment,
				      params->require_keys)) {
		fprintf(stderr, "%s Can't add hashes to FIT blob\n",
			params->cmdname);
		goto err_add_hashes;
	}

	/* for first image creation, add a timestamp at offset 0 i.e., root  */
	if (params->datafile && fit_set_timestamp(ptr, 0, sbuf.st_mtime)) {
		fprintf (stderr, "%s: Can't add image timestamp\n",
				params->cmdname);
		goto err_add_timestamp;
	}
	debug ("Added timestamp successfully\n");

	munmap ((void *)ptr, sbuf.st_size);
	close (tfd);
	if (dest_blob) {
		munmap(dest_blob, destfd_size);
		close(destfd);
	}

	if (rename (tmpfile, params->imagefile) == -1) {
		fprintf (stderr, "%s: Can't rename %s to %s: %s\n",
				params->cmdname, tmpfile, params->imagefile,
				strerror (errno));
		unlink (tmpfile);
		unlink (params->imagefile);
		return (EXIT_FAILURE);
	}
	return (EXIT_SUCCESS);

err_add_timestamp:
err_add_hashes:
	munmap(ptr, sbuf.st_size);
err_mmap:
	if (dest_blob)
		munmap(dest_blob, destfd_size);
err_keydest:
err_system:
	unlink(tmpfile);
	return -1;
}