Exemple #1
1
DAQ_LINKAGE int daq_load_modules(const char *directory_list[])
{
    static const char *extension = MODULE_EXT;
#ifndef WIN32
    char dirpath[NAME_SIZE];
    DIR *dirp;
    struct dirent *de;
    char *p;
    int ret;

#ifdef STATIC_MODULE_LIST
    load_static_modules();
#endif

    for (; directory_list && *directory_list; directory_list++)
    {
        if (!(**directory_list))
            continue;
        if ((dirp = opendir(*directory_list)) == NULL)
        {
            fprintf(stderr,"Unable to open directory \"%s\"\n", *directory_list);
            continue;
        }

        DEBUG("Loading modules in: %s\n", *directory_list);

        while((de = readdir(dirp)) != NULL)
        {
            if (de->d_name == NULL)
                continue;
            p = strrchr(de->d_name, '.');
            if (!p || strcmp(p, extension))
                continue;
            snprintf(dirpath, sizeof(dirpath), "%s/%s", *directory_list, de->d_name);

            ret = daq_load_module(dirpath);
            if (ret == DAQ_SUCCESS)
            {
                DEBUG("Found module %s\n", de->d_name);
            }
            else if (ret == DAQ_ERROR_NOMEM)
            {
                closedir(dirp);
                return DAQ_ERROR_NOMEM;
            }
        }
        closedir(dirp);
    }
#else
    /* Find all shared library files in path */
    char path_buf[PATH_MAX];
    char dyn_lib_name[PATH_MAX];
    char drive[_MAX_DRIVE];
    char dir[_MAX_DIR];
    char fname[_MAX_FNAME];
    char ext[_MAX_EXT];
    HANDLE fSearch;
    WIN32_FIND_DATA FindFileData;
    int pathLen = 0;
    const char *directory;
    int useDrive = 0;

#ifdef STATIC_MODULE_LIST
    load_static_modules();
#endif

    for (; directory_list && *directory_list; directory_list++)
    {
        if (!(**directory_list))
            continue;

        if ((strncpy(path_buf, *directory_list, PATH_MAX) == NULL) ||
            (strlen(path_buf) != strlen(*directory_list)))
        {
            fprintf(stderr, "Path is too long: %s\n", *directory_list);
            continue;
        }

        pathLen = strlen(path_buf);
        if ((path_buf[pathLen - 1] == '\\') ||
            (path_buf[pathLen - 1] == '/'))
        {
            /* A directory was specified with trailing dir character */
            _splitpath(path_buf, drive, dir, fname, ext);
            _makepath(path_buf, drive, dir, "*", MODULE_EXT);
            directory = &dir[0];
            useDrive = 1;
        }
        else /* A directory was specified */
        {
            _splitpath(path_buf, drive, dir, fname, ext);
            if (strcmp(extension, ""))
            {
                fprintf(stderr, "Improperly formatted directory name: %s\n", *directory_list);
                continue;
            }

            _makepath(path_buf, "", path_buf, "*", MODULE_EXT);
            directory = *directory_list;
        }

        fSearch = FindFirstFile(path_buf, &FindFileData);
        while (fSearch != NULL && fSearch != (HANDLE)-1)
        {
            if (useDrive)
                _makepath(dyn_lib_name, drive, directory, FindFileData.cFileName, NULL);
            else
                _makepath(dyn_lib_name, NULL, directory, FindFileData.cFileName, NULL);

            daq_load_module(dyn_lib_name);

            if (!FindNextFile(fSearch, &FindFileData))
            {
                break;
            }
        }
        FindClose(fSearch);
    }
#endif
    return DAQ_SUCCESS;
}
Exemple #2
1
int main(){
    int i,line;
    char content[MAX_SCHEDULER][MAXLINE];
    int pipe_fd[2];
    FILE* fptr,*tmp_fptr;
    struct dirent *dirp;
    DIR* dp;
    pid_t pid;
    if((dp=opendir(dirname))==NULL)
        err_sys();
    while((dirp=readdir(dp))!=NULL)
        if(strcmp(dirp->d_name,".")==0 || strcmp(dirp->d_name,"..")==0)
            continue;
        else
            break;
    if(dirp==NULL)
        _Exit(0);
    if((tmp_fptr=fopen(tmp_filename,"w"))==NULL)
        err_sys();
    if(pipe(pipe_fd)<0)
        err_sys();
    if((pid=fork())<0){
        err_sys();
    }else if(pid>0){ //parent , read from pipe
        close(pipe_fd[1]);
        if((fptr=fdopen(pipe_fd[0],"r"))==NULL)
            err_sys();
        for(line=0;fgets(content[line],MAXLINE,fptr)>0;line++);
        if(fclose(fptr)==-1)
            err_sys();
        if(waitpid(pid,NULL,0)<0)
            err_sys();
    }else{ //child , write to pipe
        close(pipe_fd[0]);
        if(pipe_fd[1] != STDOUT_FILENO){
            if(dup2(pipe_fd[1],STDOUT_FILENO) != STDOUT_FILENO)
                err_sys();
            close(pipe_fd[1]);
        }
        if(execl("/usr/bin/crontab","crontab","-l",NULL)<0)
            err_sys();
    }
    deal_content(content,&line,dp,dirp);
    if(closedir(dp))
        err_sys();
    for(i=0;i<line;i++)
        fprintf(tmp_fptr,"%s",content[i]);
    if(fclose(tmp_fptr)==-1)
        err_sys();
    if((pid=fork())<0){
        err_sys();
    }else if(pid>0){ //parent
        if(waitpid(pid,NULL,0)<0)
            err_sys();
    }else{ //child
        if(execl("/usr/bin/crontab","crontab",tmp_filename,NULL)<0)
            err_sys();
    }
    if(unlink(tmp_filename)==-1)
        err_sys();
    return 0;
}
void    dumpDirectoryContentsIntoRawFile(char *dir, int fd) {
    DIR           *FD = NULL;
    struct dirent *in_file;
    char          *imagePath;

    // loop over image stack - in order //
    if (NULL == (FD = opendir(dir)))
    {
        fprintf(stderr, "Error : Failed to open input directory - %s\n", strerror(errno));
        free(FD);
        return;
    }

    while ((in_file = readdir(FD)))
    {
        printf("Processing %s\n", in_file->d_name);
        if (!strcmp (in_file->d_name, "."))
            continue;
        if (!strcmp (in_file->d_name, ".."))
            continue;
        //APPLE Dir ISSUE
        if (!strcmp (in_file->d_name, ".DS_Store"))
            continue;

        asprintf(&imagePath, "%s/%s", dir, in_file->d_name);
        appendImageBytesToRaw(fd, imagePath);
    }
    closedir(FD);


    // loop over image stack - strange behaviour (revise order) //
    /*
     int n;
     struct dirent **namelist;

     n = scandir(dir, &namelist, 0, alphasort);
     // error scanning directory
     if (n < 0) {
        perror("scandir");
        exit(-1);
     }
     */
    /*
    while(n--) {
        printf("Processing %s\n", namelist[n]->d_name);

        if (!strcmp (namelist[n]->d_name, "."))
            continue;
        if (!strcmp (namelist[n]->d_name, ".."))
            continue;
        //APPLE Dir ISSUE
        if (!strcmp (namelist[n]->d_name, ".DS_Store"))
            continue;

        asprintf(&imagePath, "%s/%s", dir, namelist[n]->d_name);
        appendImageBytesToRaw(fd, imagePath);
        free(namelist[n]);
    }
    free(namelist);
    */
}
void ModelDB::parseModelFileDir(string dirName){
#ifdef USE_GCC
    DIR * dirp = opendir(dirName.c_str());
    struct dirent * dp;
    ifstream fin(dirName.c_str());

    // if the path is a directory, parse the each model in this directory
    // ASSUMPTION: here it is only a two tier structure. no recursive reading.
    if (dirp) {

	errno = 0;
	// read each file
	while (( dp = readdir(dirp)) != NULL) {
	    // if the file is . or .., skip it	
	    if(!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")){
		continue; // do nothing for "useless" directories
	    }
	    // if the file ends with ~, skip it also
	    if (dp->d_name[strlen(dp->d_name)-1]=='~') {
		continue;
	    }
	    // otherwise, use the fileName as the modelID
	    string modelID(dp->d_name);
	    string fullpath=dirName+"/"+dp->d_name;
	    // parse the single model file then
	    parseSingleModelFile(fullpath, modelID);
	}
    }
    // if the path is a file, use the file name as the modelID
    else if (fin) {
	bDir = false;
	int pos = dirName.find_last_of("/");
	if (pos!=-1) {
	    string modelID(dirName.substr(pos+1));
	    parseSingleModelFile(dirName,modelID);
	}
	else {
	    parseSingleModelFile(dirName,dirName);
	}
    }
    // otherwise, error msg
    else{
	cerr << "\n parseDirectoryModel: Can't open directory " << dirName << endl;
	exit (1);
    } 
#endif //USE_GCC

#ifdef _MSC_VER
    // I couldn't find good apis to read a directory. If this is the only
    // way, then I don't understand why microsoft doesn't provide a better
    // wrapper for these functions. -- Bing Bai.  

    long hfile = -1;
    int  status = 0;
    char fullpath[MAXPATHLEN] = {0};
    int curDrive;
    char curPath[MAXPATHLEN];
    
    // store the information of the file/directory
    struct stat st;    

    // preprocess the name, get rid the last char if it is '\'
    if(dirName.at(dirName.length()-1)=='\\') {
	dirName = dirName.substr(0, dirName.length()-1);
    }

    // if it is not empty
    if( stat(dirName.c_str(), &st)==0 ){
	// if is a directory
	if (st.st_mode & _S_IFDIR) {
	    // keep the current driver and path info
	    curDrive = _getdrive();
	    _getcwd(curPath, MAXPATHLEN);
	    // go into the directory
	    status = _chdir(dirName.c_str());
	    // check each file in the directory
	    SearchDirectory((char*)dirName.c_str());
	    // go back to the original place
	    _chdrive(curDrive);
	    _chdir(curPath);
	}
	// if it is a file
	else {
	    bDir = false;
	    int pos = dirName.find_last_of("\\");
	    if (pos!=-1) {
		string modelID(dirName.substr(pos+1));
		parseSingleModelFile(dirName,modelID);
	    }
	    else {
		parseSingleModelFile(dirName,dirName);
	    }
	}
    }

#endif //_MSC_VER
}
Exemple #5
0
static int  inotify_test(void)
{
	int inotify_fd;
	DIR *director_watch;
	struct dirent *de;


	inotify_fd = open_inotify_fd();
	if (inotify_fd > 0) {
		/* We will need a place to enqueue inotify events,
		   this is needed because if you do not read events
		   fast enough, you will miss them. This queue is
		   probably too small if you are monitoring something
		   like a directory with a lot of files and the directory
		   is deleted.
		*/
		queue_t q;
		q = queue_create(128);

		/* This is the watch descriptor returned for each item we are
	           watching. A real application might keep these for some use
	           in the application. This sample only makes sure that none of
	           the watch descriptors is less than 0.
	        */


		/* Watch all events (IN_ALL_EVENTS) for the directories and
	           files passed in as arguments.
	           Read the article for why you might want to alter this for
	           more efficient inotify use in your app.
	        */
		int index;
		wd = 0;
		printf("\n");
		/* for (index = 1; (index < argc) && wd >= 0); index++) { */
		/* 	wd = watch_dir(inotify_fd, argv[index], IN_ALL_EVENTS); */
		/* } */

		director_watch = opendir(WATCH_PATH);
		if (director_watch == 0)
			return;
		while((de = readdir(director_watch)) != 0) {
			if(bad_name(de->d_name))
				   continue;
			snprintf(busname, sizeof busname, "%s/%s", WATCH_PATH, de->d_name);		  

			int wd = watch_dir(inotify_fd, busname, IN_DELETE | IN_CREATE);
			if (wd > 0){
				LOG("chiplua add %s", busname);
			}
			process_inotify_events(q, inotify_fd);
		}	     
		return 0;
	}
	
	/* wd = watch_dir(inotify_fd, WATCH_PATH, IN_DELETE | IN_CREATE); */
	/* if (wd > 0) { */
	/* 	/\* Wait for events and process them until a */
	/* 	   temination condition is detected. */
	/* 	*\/ */
	/* 	process_inotify_events(q, inotify_fd); */
	/* } */
	/* printf("\nTerminating\n"); */

	/* /\* Finish up by closing the fd, destroying the queue, */
	/*    and returning a proper code. */
	/* *\/ */
	/* close_inotify_fd(inotify_fd); */
	/*queue_destroy(q); */
	
}
Exemple #6
0
int
main(int argc, char *argv[])
{
    MPLS_PL *pl;
    int opt;
    int ii, pl_ii;
    MPLS_PL *pl_list[1000];
    struct stat st;
    str_t path = {0,};
    DIR *dir = NULL;

    do {
        opt = getopt(argc, argv, OPTS);
        switch (opt) {
            case -1: 
                break;

            case 'v':
                verbose = 1;
                break;

            case 'l':
                clip_list = 1;
                break;

            case 'i':
                playlist_info = 1;
                break;

            case 'c':
                chapter_marks = 1;
                break;

            case 'd':
                dups = 1;
                break;

            case 'r':
                repeats = atoi(optarg);
                break;

            case 'f':
                repeats = 2;
                dups = 1;
                seconds = 120;
                break;

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

            default:
                _usage(argv[0]);
                break;
        }
    } while (opt != -1);

    if (optind >= argc) {
        _usage(argv[0]);
    }

    for (pl_ii = 0, ii = optind; pl_ii < 1000 && ii < argc; ii++) {
        if (stat(argv[ii], &st)) {
            continue;
        }
        dir = NULL;
        if (S_ISDIR(st.st_mode)) {
            printf("Directory: %s:\n", argv[ii]);
            _make_path(&path, argv[ii], "PLAYLIST");
            if (path.buf == NULL) {
                fprintf(stderr, "Failed to find playlist path: %s\n", argv[ii]);
                continue;
            }
            dir = opendir(path.buf);
            if (dir == NULL) {
                fprintf(stderr, "Failed to open dir: %s\n", path.buf);
                str_free(&path);
                continue;
            }
        }
        if (dir != NULL) {
            char **dirlist = calloc(10001, sizeof(char*));
            struct dirent *ent;
            int jj = 0;
            for (ent = readdir(dir); ent != NULL; ent = readdir(dir)) {
                if (ent->d_name != NULL) {
                    dirlist[jj++] = strdup(ent->d_name);
                }
            }
            qsort(dirlist, jj, sizeof(char*), _qsort_str_cmp);
            for (jj = 0; dirlist[jj] != NULL; jj++) {
                str_t name = {0,};
                str_printf(&name, "%s/%s", path.buf, dirlist[jj]);
                free(dirlist[jj]);
                if (stat(name.buf, &st)) {
                    str_free(&name);
                    continue;
                }
                if (!S_ISREG(st.st_mode)) {
                    str_free(&name);
                    continue;
                }
                pl = _process_file(name.buf, pl_list, pl_ii);
                str_free(&name);
                if (pl != NULL) {
                    pl_list[pl_ii++] = pl;
                }
            } while (ent != NULL);
            free(dirlist);
            str_free(&path);
        } else {
            pl = _process_file(argv[ii], pl_list, pl_ii);
            if (pl != NULL) {
                pl_list[pl_ii++] = pl;
            }
        }
    }
    // Cleanup
    for (ii = 0; ii < pl_ii; ii++) {
        mpls_free(&pl_list[ii]);
    }
    return 0;
}
Exemple #7
0
int main (int argc, char *argv[])
{
   char c;
   char plugins[100][100], s[20];
   char romfile[PATH_MAX];
   int old_i, i, i1, i2, i3, i4;
   int p, p_fullscreen = 0, p_emumode = 0, p_gfx = 0, p_audio = 0, p_input = 0, p_rsp = 0, p_help = 0, p_error = 0;
   int p_emumode_value=1, fileloaded = 0, p_interactive = 0;
   int true = 1;
   char *buffer, *buffer2;
   
#if defined (__linux__)
   if (signal(SIGTERM, sigterm_handler) == SIG_ERR)
     printf("Warning: Couldn't register SIGTERM signal handler!\n");
#endif
   
   //Set working dir
#ifdef WITH_HOME
     {
	char temp[PATH_MAX], orig[PATH_MAX];
	FILE *src, *dest;
	struct dirent *entry;
	DIR *dir;
	
	strcpy(g_WorkingDir, getenv("HOME"));
	strcat(g_WorkingDir, "/.mupen64/");
	strcpy(cwd, g_WorkingDir);
	mkdir(g_WorkingDir, 0700);
	
	strcpy(temp, g_WorkingDir);
	strcat(temp, "mupen64.ini");
	dest = fopen(temp, "rb");
	if (dest == NULL)
	  {
	     unsigned char byte;
	     dest = fopen(temp, "wb");
	     strcpy(orig, WITH_HOME);
	     strcat(orig, "share/mupen64/mupen64.ini");
	     src = fopen(orig, "rb");
	     while(fread(&byte, 1, 1, src))
	       fwrite(&byte, 1, 1, dest);
	     fclose(src);
	     fclose(dest);
	  }
	else fclose(dest);
	
	strcpy(temp, g_WorkingDir);
	strcat(temp, "lang");
	strcpy(orig, WITH_HOME);
	strcat(orig, "share/mupen64/lang");
	symlink(orig, temp);
	
	/*strcpy(temp, g_WorkingDir);
	strcat(temp, "plugins");
	strcpy(orig, WITH_HOME);
	strcat(orig, "share/mupen64/plugins");
	symlink(orig, temp);*/
	
	strcpy(temp, g_WorkingDir);
	strcat(temp, "plugins");
	mkdir(temp, 0700);
	strcpy(orig, WITH_HOME);
	strcat(orig, "share/mupen64/plugins");
	dir = opendir(orig);
	while((entry = readdir(dir)) != NULL)
	  {
	     if(strcmp(entry->d_name + strlen(entry->d_name) - 3, ".so"))
	       {
		  strcpy(orig, WITH_HOME);
		  strcat(orig, "share/mupen64/plugins/");
		  strcat(orig, entry->d_name);
		  src = fopen(orig, "rb");
		  if(src == NULL) continue;
		  
		  strcpy(temp, g_WorkingDir);
		  strcat(temp, "plugins/");
		  strcat(temp, entry->d_name);
		  dest = fopen(temp, "rb");
		  if(dest == NULL)
		    {
		       unsigned char byte;
		       dest = fopen(temp, "wb");
		       while(fread(&byte, 1, 1, src))
			 fwrite(&byte, 1, 1, dest);
		       fclose(src);
		       fclose(dest);
		    }
		  else fclose(dest);
	       }
	     else
	       {
		  strcpy(temp, g_WorkingDir);
		  strcat(temp, "plugins/");
		  strcat(temp, entry->d_name);
		  strcpy(orig, WITH_HOME);
		  strcat(orig, "share/mupen64/plugins/");
		  strcat(orig, entry->d_name);
		  symlink(orig, temp);
	       }
	  }
	
	strcpy(temp, g_WorkingDir);
	strcat(temp, "save/");
	mkdir(temp, 0700);
	
	chdir(g_WorkingDir);
     }
#else
   if (argv[0][0] != '/')
     {
	getcwd(cwd, 1024);
	strcat(cwd, "/");
	strcat(cwd, argv[0]);
     }
   else
     strcpy(cwd, argv[0]);
   while(cwd[strlen(cwd)-1] != '/') cwd[strlen(cwd)-1] = '\0';
   strcpy(g_WorkingDir, cwd);
#endif
   
   //read config file, read plugins
   config_read();
   plugin_scan_directory(cwd);
   
   //get config file settings
   
   buffer = (char*)config_get_string("Gfx Plugin", "");
   buffer2= plugin_name_by_filename(buffer);
   if(buffer2)
     {
	strcpy(plugins[100], buffer2);
	p_gfx = true;
     }
   else if(buffer) printf("GFX Plugin from ini-file could not be loaded\n");
   
   buffer = (char*)config_get_string("Audio Plugin", "");
   buffer2= plugin_name_by_filename(buffer);
   if(buffer2)
     {
	strcpy(plugins[99], buffer2);
	p_audio = true;
     }
   else if(buffer) printf("Audio Plugin from ini-file could not be loaded\n");
   
   buffer = (char*)config_get_string("Input Plugin", "");
   buffer2= plugin_name_by_filename(buffer);
   if(buffer2)
     {
	strcpy(plugins[98], buffer2);
	p_input = true;
     }
   else if(buffer) printf("Input Plugin from ini-file could not be loaded\n");
   
   buffer = (char*)config_get_string("RSP Plugin", "");
   buffer2= plugin_name_by_filename(buffer);
   if(buffer2)
     {
	strcpy(plugins[97], buffer2);
	p_rsp = true;
     }
   else if(buffer) printf("RSP Plugin from ini-file could not be loaded\n");
   
   buffer = (char*)config_get_string("Core", "");
   if(strcmp(buffer,""))
     {
	p_emumode = true;
	p_emumode_value = buffer[0]-'0'+1;
     }
   
   buffer = (char*)config_get_string("Fullscreen", "");
   if(strcmp(buffer,""))
     {
	if(!strcmp(buffer, "true"))
	  p_fullscreen = true;
     }
   
   buffer = (char*)config_get_string("No Ask", "");
   if(strcmp(buffer,""))
     {
	if(!strcmp(buffer, "true"))
	  p_noask = true;
     }
   
   // Command Line Parameter - Parsing
   
   for(p=1; p<argc; p++)
     {
	if(argv[p][0] == '-')
	  {
	     if(!strcmp(argv[p], "--fullscreen"))
	       p_fullscreen = true;
	     else if(!strcmp(argv[p], "--help"))
	       p_help = true;
	     else if(!strcmp(argv[p], "--noask"))
	       p_noask = true;
	     else if(!strcmp(argv[p], "--interactive"))
	       p_interactive = true;
	     else if(!strcmp(argv[p], "--emumode"))
	       {
		  p++;
		  if(p < argc)
		    {
		       p_emumode_value = argv[p][0];
		       p_emumode = true;
		    }
	       }
	     else if(!strcmp(argv[p], "--gfx"))
	       {
		  p++;
		  if(p < argc)
		    {
		       buffer = plugin_name_by_filename(argv[p]);
		       if(buffer)
			 {
			    strcpy(plugins[100], buffer);
			    p_gfx = true;
			 }
		       else printf("specified GFX Plugin couldn't be loaded!\n");
		    }
	       }
	     else if(!strcmp(argv[p], "--audio"))
	       {
		  p++;
		  if(p < argc)
		    {
		       buffer = plugin_name_by_filename(argv[p]);
		       if(buffer)
			 {
			    strcpy(plugins[99], buffer);
			    p_audio = true;
			 }
		       else printf("specified Audio Plugin couldn't be loaded!\n");
		    }
	       }
	     else if(!strcmp(argv[p], "--input"))
	       {
		  p++;
		  if(p < argc)
		    {
		       buffer = plugin_name_by_filename(argv[p]);
		       if(buffer)
			 {
			    strcpy(plugins[98], buffer);
			    p_input = true;
			 }
		       else printf("specified Input Plugin couldn't be loaded!\n");
		    }
	       }
	     else if(!strcmp(argv[p], "--rsp"))
	       {
		  p++;
		  if(p < argc)
		    {
		       buffer = plugin_name_by_filename(argv[p]);
		       if(buffer)
			 {
			    strcpy(plugins[97], buffer);
			    p_rsp = true;
			 }
		       else printf("specified RSP Plugin couldn't be loaded!\n");
		    }
	       }
	  }
	else
	  {
	     strcpy(romfile, argv[p]);
	     fileloaded = true;
	  }
     }
   
   if(p_interactive)
     {
	p_emumode = 0;
	p_gfx = 0;
	p_audio = 0;
	p_input = 0;
	p_rsp = 0;
     }
   
   printf("\nMupen64 version : %s\n", VERSION);
   
   if (argc < 2 || p_help || p_error || fileloaded != true)
     {
	printf("\n\n"
	       "syntax: mupen64_nogui [parameter(s)] rom\n"
	       "\n"
	       "Parameters:\n"
	       "  --fullscreen       : turn fullscreen mode on\n"
	       "  --gfx (plugin)     : set gfx plugin to (plugin)\n"
	       "  --audio (plugin)   : set audio plugin to (plugin)\n"
	       "  --input (plugin)   : set input plugin to (plugin)\n"
	       "  --rsp (plugin)     : set rsp plugin to (plugin)\n"
	       "  --emumode (number) : set emu mode to: 1=interp./2=recomp./3=pure interp\n"
	       "  --noask            : don't ask to force load on bad dumps\n"
	       "  --interactive      : ask interactively for all plugins\n"
	       "\n"
	       "You can also use the Config-File from the Gui-Version\n"
	       "but there are aditional Parameters for the NO-GUI Version\n"
	       "\n");
	return 0;
     }
   
   if (rom_read(romfile))
     {
	if(rom) free(rom);
	if(ROM_HEADER) free(ROM_HEADER);
	return 1;
     }
   printf("Goodname:%s\n", ROM_SETTINGS.goodname);
   printf("16kb eeprom=%d\n", ROM_SETTINGS.eeprom_16kb);
   printf ("emulation mode:\n"
	   "     1. interpreter\n"
	   "     2. dynamic recompiler (default)\n"
           "     3. pure interpreter\n");
   
   if(p_emumode)
     c = p_emumode_value;
   else
     c = getchar();
   
   if (c == '1') dynacore=0;
   else if (c == '3') dynacore=2;
   else dynacore=1;
   
   SDL_Init(SDL_INIT_VIDEO);
   SDL_SetVideoMode(10, 10, 16, 0);
   SDL_ShowCursor(0);
   SDL_EnableKeyRepeat(0, 0);
   SDL_EnableUNICODE(1);
   init_memory();
   // --------------------- loading plugins ----------------------
   i=1;
   i1=1;
   printf("  Choose your gfx plugin : \n");
   while(plugin_type() != -1)
     {
	if (plugin_type() == PLUGIN_TYPE_GFX)
	  {
	     strcpy(plugins[i], plugin_next());
	     printf("%s (%s)\n", plugins[i], plugin_filename_by_name(plugins[i]));
	     i++;
	  }
	else
	  plugin_next();
     }
   
   if(p_gfx)
     i1 = 100;
   else
     {
	if(p_emumode)
	  getchar();
	/*c = getchar();
	 s[0] = c;
	 s[1] = 0;*/
	scanf("%10s", s);
	i1 = atoi(s);
     }
   
   plugin_rewind();
   old_i = i;
   printf("  Choose your audio plugin : \n");
   while(plugin_type() != -1)
     {
	if (plugin_type() == PLUGIN_TYPE_AUDIO)
	  {
	     strcpy(plugins[i], plugin_next());
	     printf("%s (%s)\n", plugins[i], plugin_filename_by_name(plugins[i]));
	     i++;
	  }
	else
	  plugin_next();
     }
   /*getchar();
   c = getchar();
   //getchar();
   s[0] = c;
   s[1] = 0;*/
   if(p_audio)
     i2 = 99;
   else
     {
	scanf("%10s", s);
	i2 = old_i + atoi(s) - 1;
     }
   
   plugin_rewind();
   old_i = i;
   printf("  Choose your input plugin : \n");
   while(plugin_type() != -1)
     {
	if (plugin_type() == PLUGIN_TYPE_CONTROLLER)
	  {
	     strcpy(plugins[i], plugin_next());
	     printf("%s (%s)\n", plugins[i], plugin_filename_by_name(plugins[i]));
	     i++;
	  }
	else
	  plugin_next();
     }
   /*getchar();
   c = getchar();
   //getchar();
   s[0] = c;
   s[1] = 0;*/
   if(p_input)
     i3 = 98;
   else
     {
	scanf("%10s", s);
	i3 = old_i + atoi(s) - 1;
     }
   
   plugin_rewind();
   old_i = i;
   printf("  Choose your RSP plugin : \n");
   while(plugin_type() != -1)
     {
	if (plugin_type() == PLUGIN_TYPE_RSP)
	  {
	     strcpy(plugins[i], plugin_next());
	     printf("%s (%s)\n", plugins[i], plugin_filename_by_name(plugins[i]));
	     i++;
	  }
	else
	  plugin_next();
     }
   /*getchar();
   c = getchar();
   getchar();
   s[0] = c;
   s[1] = 0;*/
   if(p_rsp)
     i4 = 97;
   else
     {
	scanf("%10s", s);
	i4 = old_i + atoi(s) - 1;
     }
   
   printf("\n\nSelected Plugins: %s, %s, %s, %s\n", plugins[i1], plugins[i2], plugins[3], plugins[i4]);
   
   plugin_load_plugins(plugins[i1], plugins[i2], plugins[i3], plugins[i4]);
   romOpen_gfx();
   romOpen_audio();
   romOpen_input();
   // ------------------------------------------------------------
   SDL_SetEventFilter(filter);
   
   if(p_fullscreen)
     changeWindow();
   
   go();
   romClosed_RSP();
   romClosed_input();
   romClosed_audio();
   romClosed_gfx();
   closeDLL_RSP();
   closeDLL_input();
   closeDLL_audio();
   closeDLL_gfx();
   free(rom);
   free(ROM_HEADER);
   free_memory();
   return 0;
}
Exemple #8
0
static void
find_all_disks (void)
{
  DIR *dir;
  struct dirent *d;
  size_t nr_disks = 0, nr_removable = 0;
  dev_t root_device = 0;
  struct stat statbuf;

  if (stat ("/", &statbuf) == 0)
    root_device = statbuf.st_dev;

  /* The default list of disks is everything in /sys/block which
   * matches the common patterns for disk names.
   */
  dir = opendir ("/sys/block");
  if (!dir) {
    perror ("opendir");
    exit (EXIT_FAILURE);
  }

  for (;;) {
    errno = 0;
    d = readdir (dir);
    if (!d) break;

    if (STRPREFIX (d->d_name, "cciss!") ||
        STRPREFIX (d->d_name, "hd") ||
        STRPREFIX (d->d_name, "sd") ||
        STRPREFIX (d->d_name, "ubd") ||
        STRPREFIX (d->d_name, "vd")) {
      char *p;

      /* Skip the device containing the root filesystem. */
      if (device_contains (d->d_name, root_device))
        continue;

      nr_disks++;
      all_disks = realloc (all_disks, sizeof (char *) * (nr_disks + 1));
      if (!all_disks) {
        perror ("realloc");
        exit (EXIT_FAILURE);
      }

      all_disks[nr_disks-1] = strdup (d->d_name);

      /* cciss device /dev/cciss/c0d0 will be /sys/block/cciss!c0d0 */
      p = strchr (all_disks[nr_disks-1], '!');
      if (p) *p = '/';

      all_disks[nr_disks] = NULL;
    }
    else if (STRPREFIX (d->d_name, "sr")) {
      nr_removable++;
      all_removable = realloc (all_removable,
                               sizeof (char *) * (nr_removable + 1));
      if (!all_removable) {
        perror ("realloc");
        exit (EXIT_FAILURE);
      }
      all_removable[nr_removable-1] = strdup (d->d_name);
      all_removable[nr_removable] = NULL;
    }
  }

  /* Check readdir didn't fail */
  if (errno != 0) {
    perror ("readdir: /sys/block");
    exit (EXIT_FAILURE);
  }

  /* Close the directory handle */
  if (closedir (dir) == -1) {
    perror ("closedir: /sys/block");
    exit (EXIT_FAILURE);
  }

  if (all_disks)
    qsort (all_disks, nr_disks, sizeof (char *), compare);
  if (all_removable)
    qsort (all_removable, nr_removable, sizeof (char *), compare);
}
void MainWindow::on_object_id_textChanged(const QString &arg1)
{
    // show all faces allready taged with the id of the object_id field
    QString id = ui->object_id->text();

    std::vector<QPixmap> listCrops;

    QString dir_name = Manager::exemplar()->selectedDirectory;//"/home/daniel/BaoDataBase/myDataBase";
    // collect all FaceObjects and imagees with the given id
    DIR *dir;
    struct dirent *ent;
    struct stat info;
    const char *c_str2 = dir_name.toLocal8Bit().data();
    if ((dir = opendir (c_str2)) != NULL) {
      /* print all the files and directories within directory */
      while ((ent = readdir (dir)) != NULL) {
          stat(ent->d_name, &info);
          //if(!S_ISDIR (info.st_mode)) {
            //qDebug() << ent->d_name;
            std::vector<FaceObject> list = readObjectFile(dir_name.toStdString() + "/.metaface/" + ent->d_name + ".txt");
            if(list.size() > 0) {
                for(std::vector<FaceObject>::iterator it = list.begin(); it != list.end(); ++it) {
                    FaceObject fo = *it;
                    if(fo.objectID == id.toStdString()) {
                        qDebug() << "found a face in:" << ent->d_name;
                        QPixmap * img = new QPixmap();
                        QString fileName = QString::fromStdString(ent->d_name);
                        img->load(dir_name + "/" + fileName);
                        //QPixmap::copy(int x, int y, int width, int height )
                        QPixmap imgCroped = img->copy(fo.x, fo.y, fo.width, fo.height);
                        qDebug() << "image crop x:" << fo.x << "y:" << fo.y << "width" << fo.width << "height:" << fo.height;
                        listCrops.push_back(imgCroped);
                    }

                }
            }
      }
      closedir (dir);
    }

    // check how many croped faces are stored in the list
    qDebug() << "there are " << listCrops.size() << " store in the vector";



    //QString imgPath = "/home/daniel/facetag/datasettools2/datasettools80.png";
    //QImage *img = new QImage();
    //bool loaded = img->load(imgPath);
    //if (loaded)
    //{
        /*QTableWidgetItem *thumbnail = new QTableWidgetItem;
        thumbnail->setData(Qt::DecorationRole, QPixmap::fromImage(*img));

        //thumbnailsWidget->setColumnCount(3);
        //thumbnailsWidget->setRowCount(3);
        ui->tableIamges->setItem(0, 0, thumbnail);*/

        //w.setCentralWidget(thumbnailsWidget);
    //} else {
        //qDebug()<<"Image "<<imgPath<<" was not opened!";
   // }
        int row = 0;
        int column = 0;
        int cell = 0;
        for(std::vector<QPixmap>::iterator it = listCrops.begin(); it != listCrops.end(); ++it) {
            QPixmap pm = *it;
            pm = pm.scaledToHeight(80,Qt::SmoothTransformation);
            QTableWidgetItem *thumbnail = new QTableWidgetItem;
            thumbnail->setData(Qt::DecorationRole, pm);
            ui->tableIamges->setItem(column, row, thumbnail);
            if(column == 2) {
                row++;
                cell++;
                column = 0;
            } else {
                row++;
                cell++;
            }
        }

        int maxCells = ui->tableIamges->rowCount() * ui->tableIamges->columnCount();
        while(cell < 9) {
            QTableWidgetItem *thumbnail = new QTableWidgetItem;
            ui->tableIamges->setItem(column, row, thumbnail);
            if(column == 2) {
                row++;
                cell++;
                column = 0;
            } else {
                row++;
                cell++;
            }
        }
}
char * findVideoDevice(const char *name)
{
    if(name == NULL) return NULL;
    DIR * d;
    char * video_pattern = "video";
    size_t video_pattern_len = strlen(video_pattern);
    size_t name_len = strlen(name);
    char * dir_name = "/dev/";
    char * result = NULL;

    printf("[UVC Cam ] Start finding video device\n");

    d = opendir (dir_name);
    if (! d) {
        fprintf (stderr, "Cannot open directory '%s': %s\n",
                 dir_name, strerror (errno));
        exit (EXIT_FAILURE);
    }
    while (1) {
        try{
            struct dirent * entry;
            entry = readdir (d);
            if (! entry) {
                break;
            }
            // if it is not a video device continue
            if(strncmp(video_pattern,entry->d_name,video_pattern_len)!=0) {
                continue;
            }
            // if video device name is not correct, coninue
            char * device = (char*) malloc(strlen(dir_name)+strlen(entry->d_name)+1);
            strcpy(device,dir_name);
            strcat(device, entry->d_name);
            printf("device=%s\n",device);
            printf("entry->d_name=%s\n",entry->d_name);
            int fd = open(device, O_RDWR|O_NONBLOCK);
            printf("FIND VIDEO DEVIC, FD is %d\n",fcntl(fd, F_GETFD));
            if (fd < 0) {
                printf("fd = -1\n");
                free(device);
                continue;
            }
            struct v4l2_capability info;
            memset(&info, 0x0, sizeof(info));
            int res = ioctl(fd, VIDIOC_QUERYCAP, &info);
            close(fd);
            if (res < 0 || strncmp(name,(char*)info.card,name_len)!=0)
            {
                printf("name=%s\n",name);
                printf("info.card=%s",(char*)info.card);
                printf("Error res is %d",res);
                free(device);
                continue;
            }
            result = device;
        }catch(...){
            continue;
        }
    }
    if (closedir (d)) {
        fprintf (stderr, "Could not close '%s': %s\n",
                 dir_name, strerror (errno));
        exit (EXIT_FAILURE);
    }
    printf("[UVC Cam] find video device OK result is %s\n", result);
    return result;
}
Exemple #11
0
static void process_lua(hs_output_plugins *plugins, const char *lpath,
                        const char *rpath, DIR *dp)
{
  char lua_lpath[HS_MAX_PATH];
  char lua_rpath[HS_MAX_PATH];
  char cfg_lpath[HS_MAX_PATH];
  char cfg_rpath[HS_MAX_PATH];
  size_t tlen = strlen(hs_output_dir) + 1;

  struct dirent *entry;
  while ((entry = readdir(dp))) {
    if (hs_has_ext(entry->d_name, hs_lua_ext)) {
      // move the Lua to the run directory
      if (!hs_get_fqfn(lpath, entry->d_name, lua_lpath, sizeof(lua_lpath))) {
        hs_log(NULL, g_module, 0, "load lua path too long");
        exit(EXIT_FAILURE);
      }
      if (!hs_get_fqfn(rpath, entry->d_name, lua_rpath, sizeof(lua_rpath))) {
        hs_log(NULL, g_module, 0, "run lua path too long");
        exit(EXIT_FAILURE);
      }
      if (rename(lua_lpath, lua_rpath)) {
        hs_log(NULL, g_module, 3, "failed to move: %s to %s errno: %d",
               lua_lpath, lua_rpath, errno);
        continue;
      }

      // restart any plugins using this Lua code
      pthread_mutex_lock(&plugins->list_lock);
      for (int i = 0; i < plugins->list_cap; ++i) {
        if (!plugins->list[i]) continue;

        hs_output_plugin *p = plugins->list[i];
        if (strcmp(lua_rpath, lsb_heka_get_lua_file(p->hsb)) == 0) {
          int ret = snprintf(cfg_lpath, HS_MAX_PATH, "%s/%s%s", lpath,
                             p->name + tlen, hs_cfg_ext);
          if (ret < 0 || ret > HS_MAX_PATH - 1) {
            hs_log(NULL, g_module, 0, "load cfg path too long");
            exit(EXIT_FAILURE);
          }

          ret = snprintf(cfg_rpath, HS_MAX_PATH, "%s/%s%s", rpath,
                         p->name + tlen, hs_cfg_ext);
          if (ret < 0 || ret > HS_MAX_PATH - 1) {
            hs_log(NULL, g_module, 0, "run cfg path too long");
            exit(EXIT_FAILURE);
          }

          // if no new cfg was provided, move the existing cfg to the load
          // directory
          if (!hs_file_exists(cfg_lpath)) {
            if (rename(cfg_rpath, cfg_lpath)) {
              hs_log(NULL, g_module, 3, "failed to move: %s to %s errno: %d",
                     cfg_rpath, cfg_lpath, errno);
            }
          }
        }
      }
      pthread_mutex_unlock(&plugins->list_lock);
    }
  }
  rewinddir(dp);
}
Exemple #12
0
/* Copy files from source_dir to fs */
static errcode_t __populate_fs(ext2_filsys fs, ext2_ino_t parent_ino,
			       const char *source_dir, ext2_ino_t root,
			       struct hdlinks_s *hdlinks)
{
	const char	*name;
	DIR		*dh;
	struct dirent	*dent;
	struct stat	st;
	char		ln_target[PATH_MAX];
	unsigned int	save_inode;
	ext2_ino_t	ino;
	errcode_t	retval;
	int		read_cnt;
	int		hdlink;

	if (chdir(source_dir) < 0) {
		com_err(__func__, errno,
			_("while changing working directory to \"%s\""),
			source_dir);
		return errno;
	}

	if (!(dh = opendir("."))) {
		com_err(__func__, errno,
			_("while opening directory \"%s\""), source_dir);
		return errno;
	}

	while ((dent = readdir(dh))) {
		if ((!strcmp(dent->d_name, ".")) ||
		    (!strcmp(dent->d_name, "..")))
			continue;
		lstat(dent->d_name, &st);
		name = dent->d_name;

		/* Check for hardlinks */
		save_inode = 0;
		if (!S_ISDIR(st.st_mode) && !S_ISLNK(st.st_mode) &&
		    st.st_nlink > 1) {
			hdlink = is_hardlink(hdlinks, st.st_dev, st.st_ino);
			if (hdlink >= 0) {
				retval = add_link(fs, parent_ino,
						  hdlinks->hdl[hdlink].dst_ino,
						  name);
				if (retval) {
					com_err(__func__, retval,
						"while linking %s", name);
					return retval;
				}
				continue;
			} else
				save_inode = 1;
		}

		switch(st.st_mode & S_IFMT) {
		case S_IFCHR:
		case S_IFBLK:
		case S_IFIFO:
			retval = do_mknod_internal(fs, parent_ino, name, &st);
			if (retval) {
				com_err(__func__, retval,
					_("while creating special file "
					  "\"%s\""), name);
				return retval;
			}
			break;
		case S_IFSOCK:
			/* FIXME: there is no make socket function atm. */
			com_err(__func__, 0,
				_("ignoring socket file \"%s\""), name);
			continue;
		case S_IFLNK:
			read_cnt = readlink(name, ln_target,
					    sizeof(ln_target));
			if (read_cnt == -1) {
				com_err(__func__, errno,
					_("while trying to readlink \"%s\""),
					name);
				return errno;
			}
			ln_target[read_cnt] = '\0';
			retval = do_symlink_internal(fs, parent_ino, name,
						     ln_target, root);
			if (retval) {
				com_err(__func__, retval,
					_("while writing symlink\"%s\""),
					name);
				return retval;
			}
			break;
		case S_IFREG:
			retval = do_write_internal(fs, parent_ino, name, name,
						   root);
			if (retval) {
				com_err(__func__, retval,
					_("while writing file \"%s\""), name);
				return retval;
			}
			break;
		case S_IFDIR:
			retval = do_mkdir_internal(fs, parent_ino, name, &st,
						   root);
			if (retval) {
				com_err(__func__, retval,
					_("while making dir \"%s\""), name);
				return retval;
			}
			retval = ext2fs_namei(fs, root, parent_ino,
					      name, &ino);
			if (retval) {
				com_err(name, retval, 0);
					return retval;
			}
			/* Populate the dir recursively*/
			retval = __populate_fs(fs, ino, name, root, hdlinks);
			if (retval) {
				com_err(__func__, retval,
					_("while adding dir \"%s\""), name);
				return retval;
			}
			if (chdir("..")) {
				com_err(__func__, errno,
					_("during cd .."));
				return errno;
			}
			break;
		default:
			com_err(__func__, 0,
				_("ignoring entry \"%s\""), name);
		}

		retval =  ext2fs_namei(fs, root, parent_ino, name, &ino);
		if (retval) {
			com_err(name, retval, 0);
			return retval;
		}

		retval = set_inode_extra(fs, parent_ino, ino, &st);
		if (retval) {
			com_err(__func__, retval,
				_("while setting inode for \"%s\""), name);
			return retval;
		}

		/* Save the hardlink ino */
		if (save_inode) {
			/*
			 * Check whether need more memory, and we don't need
			 * free() since the lifespan will be over after the fs
			 * populated.
			 */
			if (hdlinks->count == hdlinks->size) {
				void *p = realloc(hdlinks->hdl,
						(hdlinks->size + HDLINK_CNT) *
						sizeof(struct hdlink_s));
				if (p == NULL) {
					com_err(name, errno,
						_("Not enough memory"));
					return errno;
				}
				hdlinks->hdl = p;
				hdlinks->size += HDLINK_CNT;
			}
			hdlinks->hdl[hdlinks->count].src_dev = st.st_dev;
			hdlinks->hdl[hdlinks->count].src_ino = st.st_ino;
			hdlinks->hdl[hdlinks->count].dst_ino = ino;
			hdlinks->count++;
		}
	}
	closedir(dh);
	return retval;
}
Exemple #13
0
/*
 * Scan the [zcp] zedlet_dir for files to exec based on the event class.
 * Files must be executable by user, but not writable by group or other.
 * Dotfiles are ignored.
 *
 * Return 0 on success with an updated set of zedlets,
 * or -1 on error with errno set.
 *
 * FIXME: Check if zedlet_dir and all parent dirs are secure.
 */
int
zed_conf_scan_dir(struct zed_conf *zcp)
{
	zed_strings_t *zedlets;
	DIR *dirp;
	struct dirent *direntp;
	char pathname[PATH_MAX];
	struct stat st;
	int n;

	if (!zcp) {
		errno = EINVAL;
		zed_log_msg(LOG_ERR, "Failed to scan zedlet dir: %s",
		    strerror(errno));
		return (-1);
	}
	zedlets = zed_strings_create();
	if (!zedlets) {
		errno = ENOMEM;
		zed_log_msg(LOG_WARNING, "Failed to scan dir \"%s\": %s",
		    zcp->zedlet_dir, strerror(errno));
		return (-1);
	}
	dirp = opendir(zcp->zedlet_dir);
	if (!dirp) {
		int errno_bak = errno;
		zed_log_msg(LOG_WARNING, "Failed to open dir \"%s\": %s",
		    zcp->zedlet_dir, strerror(errno));
		zed_strings_destroy(zedlets);
		errno = errno_bak;
		return (-1);
	}
	while ((direntp = readdir(dirp))) {
		if (direntp->d_name[0] == '.')
			continue;

		n = snprintf(pathname, sizeof (pathname),
		    "%s/%s", zcp->zedlet_dir, direntp->d_name);
		if ((n < 0) || (n >= sizeof (pathname))) {
			zed_log_msg(LOG_WARNING, "Failed to stat \"%s\": %s",
			    direntp->d_name, strerror(ENAMETOOLONG));
			continue;
		}
		if (stat(pathname, &st) < 0) {
			zed_log_msg(LOG_WARNING, "Failed to stat \"%s\": %s",
			    pathname, strerror(errno));
			continue;
		}
		if (!S_ISREG(st.st_mode)) {
			zed_log_msg(LOG_INFO,
			    "Ignoring \"%s\": not a regular file",
			    direntp->d_name);
			continue;
		}
		if ((st.st_uid != 0) && !zcp->do_force) {
			zed_log_msg(LOG_NOTICE,
			    "Ignoring \"%s\": not owned by root",
			    direntp->d_name);
			continue;
		}
		if (!(st.st_mode & S_IXUSR)) {
			zed_log_msg(LOG_INFO,
			    "Ignoring \"%s\": not executable by user",
			    direntp->d_name);
			continue;
		}
		if ((st.st_mode & S_IWGRP) && !zcp->do_force) {
			zed_log_msg(LOG_NOTICE,
			    "Ignoring \"%s\": writable by group",
			    direntp->d_name);
			continue;
		}
		if ((st.st_mode & S_IWOTH) && !zcp->do_force) {
			zed_log_msg(LOG_NOTICE,
			    "Ignoring \"%s\": writable by other",
			    direntp->d_name);
			continue;
		}
		if (zed_strings_add(zedlets, NULL, direntp->d_name) < 0) {
			zed_log_msg(LOG_WARNING,
			    "Failed to register \"%s\": %s",
			    direntp->d_name, strerror(errno));
			continue;
		}
		if (zcp->do_verbose)
			zed_log_msg(LOG_INFO,
			    "Registered zedlet \"%s\"", direntp->d_name);
	}
	if (closedir(dirp) < 0) {
		int errno_bak = errno;
		zed_log_msg(LOG_WARNING, "Failed to close dir \"%s\": %s",
		    zcp->zedlet_dir, strerror(errno));
		zed_strings_destroy(zedlets);
		errno = errno_bak;
		return (-1);
	}
	if (zcp->zedlets)
		zed_strings_destroy(zcp->zedlets);

	zcp->zedlets = zedlets;
	return (0);
}
/*
 * return first found file name starting by the ``text'' or NULL if no
 * such file can be found
 * value of ``state'' is ignored
 *
 * it's the caller's responsibility to free the returned string
 */
char *
fn_filename_completion_function(const char *text, int state)
{
	static DIR *dir = NULL;
	static char *filename = NULL, *dirname = NULL, *dirpath = NULL;
	static size_t filename_len = 0;
	struct dirent *entry;
	char *temp;
	size_t len;

	if (state == 0 || dir == NULL) {
		temp = strrchr(text, '/');
		if (temp) {
			char *nptr;
			temp++;
			nptr = el_realloc(filename, (strlen(temp) + 1) *
			    sizeof(*nptr));
			if (nptr == NULL) {
				el_free(filename);
				filename = NULL;
				return NULL;
			}
			filename = nptr;
			(void)strcpy(filename, temp);
			len = (size_t)(temp - text);	/* including last slash */

			nptr = el_realloc(dirname, (len + 1) *
			    sizeof(*nptr));
			if (nptr == NULL) {
				el_free(dirname);
				dirname = NULL;
				return NULL;
			}
			dirname = nptr;
			(void)strncpy(dirname, text, len);
			dirname[len] = '\0';
		} else {
			el_free(filename);
			if (*text == 0)
				filename = NULL;
			else {
				filename = strdup(text);
				if (filename == NULL)
					return NULL;
			}
			el_free(dirname);
			dirname = NULL;
		}

		if (dir != NULL) {
			(void)closedir(dir);
			dir = NULL;
		}

		/* support for ``~user'' syntax */

		el_free(dirpath);
		dirpath = NULL;
		if (dirname == NULL) {
			if ((dirname = strdup("")) == NULL)
				return NULL;
			dirpath = strdup("./");
		} else if (*dirname == '~')
			dirpath = fn_tilde_expand(dirname);
		else
			dirpath = strdup(dirname);

		if (dirpath == NULL)
			return NULL;

		dir = opendir(dirpath);
		if (!dir)
			return NULL;	/* cannot open the directory */

		/* will be used in cycle */
		filename_len = filename ? strlen(filename) : 0;
	}

	/* find the match */
	while ((entry = readdir(dir)) != NULL) {
		/* skip . and .. */
		if (entry->d_name[0] == '.' && (!entry->d_name[1]
		    || (entry->d_name[1] == '.' && !entry->d_name[2])))
			continue;
		if (filename_len == 0)
			break;
		/* otherwise, get first entry where first */
		/* filename_len characters are equal	  */
		if (entry->d_name[0] == filename[0]
          /* Some dirents have d_namlen, but it is not portable. */
		    && strlen(entry->d_name) >= filename_len
		    && strncmp(entry->d_name, filename,
			filename_len) == 0)
			break;
	}

	if (entry) {		/* match found */

       /* Some dirents have d_namlen, but it is not portable. */
		len = strlen(entry->d_name);

		len = strlen(dirname) + len + 1;
		temp = el_malloc(len * sizeof(*temp));
		if (temp == NULL)
			return NULL;
		(void)snprintf(temp, len, "%s%s", dirname, entry->d_name);
	} else {
		(void)closedir(dir);
		dir = NULL;
		temp = NULL;
	}

	return temp;
}
std::vector<std::string> SerialInterface::enumerate_ports()
{
        std::vector<std::string> SerialDeviceList = std::vector<std::string>();
        
        #ifdef __unix__
        
        DIR *dp;
        struct dirent *dirp;
        std::string f, d;
        std::vector<std::string>::iterator it;
        char buf[PATH_MAX];
        
        struct serial_struct serinfo;
        int fd;
        
        if ((dp = opendir("/dev/")) == NULL)
        {
                std::cerr << "Error (" << errno << ") opening /dev/" << std::endl;
        }
        else
        {
                while ((dirp = readdir(dp)) != NULL)
                {
                        f = dirp->d_name;
                        d = "/dev/" + f;
                        if (f.find("ttyS") == 0)
                        {
                                if ((fd = ::open(d.c_str(), O_RDWR|O_NONBLOCK)) < 0)
                                {
                                        std::cerr << "Cannot open port " << d << std::endl;
                                        continue;
                                }
                                
                                serinfo.reserved_char[0] = 0;
                                
                                if (::ioctl(fd, TIOCGSERIAL, &serinfo) < 0)
                                {
                                        std::cerr << "Cannot get serial info for " << d << std::endl;
                                        ::close(fd);
                                        continue;
                                }
                                
                                if (serinfo.port != 0)
                                        SerialDeviceList.push_back(d);
                                
                                ::close(fd);
                                
                                continue;
                        }
                        if (f.find("ttyUSB") == 0)
                        {
                                SerialDeviceList.push_back(d);
                        }
                }
                
                closedir(dp);
        }
        
        if ((dp = opendir("/dev/serial/by-id/")) != NULL)
        {
                while ((dirp = readdir(dp)) != NULL)
                {
                        f = dirp->d_name;
                        if (f == "." || f == "..")
                                continue;
                        f = "/dev/serial/by-id/" + f;
                        if (realpath(f.c_str(), buf));
                        {
                                f = buf;
                                SerialDeviceList.push_back(f);
                        }
                }
                
                closedir(dp);
        }
        
        #elif defined _WIN32
        
        TCHAR szDevices[65535];
        unsigned long dwChars = QueryDosDevice(NULL, szDevices, 65535);
        TCHAR *ptr = szDevices;
        TCHAR *temp_ptr;
        std::string c;
        
        while (dwChars)
        {
                int port;
                
                if (sscanf(ptr, "COM%d", &port) == 1)
                {
                        c = ptr;
                        SerialDeviceList.push_back(c);
                }
                
                temp_ptr = strchr(ptr, 0);
                dwChars -= (DWORD)((temp_ptr - ptr) / sizeof(TCHAR) + 1);
                ptr = temp_ptr + 1;
        }
        
        #endif
        
        // sort it
        sort(SerialDeviceList.begin(), SerialDeviceList.end(), doj::alphanum_less<std::string>());
        
        // remove duplicates
        SerialDeviceList.erase(std::unique(SerialDeviceList.begin(), SerialDeviceList.end()), SerialDeviceList.end());
        
        return SerialDeviceList;
}
Exemple #16
0
void deal_content(char (*content)[MAXLINE],int* line,DIR* dp,struct dirent* dirp){
    if(dirp==NULL) return;
    else{
        FILE* fptr;
        char buffer[MAXLINE],cmd[CMD_LINE]={0};
        char filename[MAXLINE];
        char id[IDSIZE];
        int i,n;
        char date[5][IDSIZE];
        int ntask; // min hour day mon week
        char option; // + - !
        int type; // YOU , CMD , RSS ...
        if(strcmp(dirp->d_name,".")!=0 && strcmp(dirp->d_name,"..")!=0){
            strcpy(filename,dirname);
            strcat(filename,"/");
            strcat(filename,dirp->d_name);
            fptr=fopen(filename,"r");
            /*fetch*/
            fscanf(fptr,"Array ( ");
            while(fscanf(fptr,"[Task%d] => Array ",&ntask)){
                fscanf(fptr,"( [type] => %s ",buffer);
                fscanf(fptr,"[id] => %s ",id);
                fscanf(fptr,"[op] => %c ",&option);
                if(option=='='){
                    fscanf(fptr,") ");
                    continue;
                }else if(option=='-' && fgetc(fptr)==')'){
                    fseek(fptr,-1,SEEK_CUR);
                    fscanf(fptr,") ");
                    continue;
                }
                //get time format
                if(strcmp(buffer,"RSS")==0){
                    type = RSS;
                    fscanf(fptr,"[circle] => ");
                    fgets(cmd,MAXLINE,fptr);
                    cmd[strlen(cmd)-1] = ' ';
                    fscanf(fptr," ");
                }else if(strcmp(buffer,"CMD")==0){
                    type = CMD;
                    // mkdir
                    sprintf(buffer,"%s/%s",dirdata,id);
                    mkdir(buffer,S_IRWXO|S_IRWXU);
                    fscanf(fptr,"[month] => %s ",date[3]);
                    fscanf(fptr,"[day] => %s ",date[2]);
                    fscanf(fptr,"[week] => %s ",date[4]);
                    fscanf(fptr,"[hour] => %s ",date[0]);
                    fscanf(fptr,"[minute] => %s ",date[1]);
                    for(i=0;i<5;i++){
                        strcat(cmd,date[i]);
                        strcat(cmd," ");
                    }
                }else if(strcmp(buffer,"YOU")==0){
                    type = YOU;
                    strcat(cmd,YOUTUBE_FORMAT);
                }else
                    err_quit("unkown cmd");
                // get home directory
                switch(type){
                case YOU:
                    strcat(cmd,"cd $ICSHOME/YOUTUBE; ");
                    break;
                case RSS:
                    strcat(cmd,"cd $ICSHOME/RSS; ");
                    break;
                case CMD:
                    sprintf(buffer,"cd $ICSDATA/%s; ",id);
                    strcat(cmd,buffer);
                    break;
                }
                // get comment
                switch(type){
                case YOU:
                    strcat(cmd,"./youtube ");
                    fscanf(fptr,"[search] => %s ",buffer);
                    if(strcmp(buffer,")")==0)
                        continue;
                    strcat(cmd,"\"");
                    strcat(cmd,buffer);
                    strcat(cmd,"\" ");
                    strcat(cmd,id);
                    strcat(cmd," >/dev/null 2>&1");
                    break;
                case CMD:
                    fscanf(fptr,"[cmd] => ");
                    strcpy(buffer,"(");
                    fgets(buffer+1,MAXLINE,fptr);
                    if(strcmp(buffer,"()\n")==0)
                        continue;
                    buffer[strlen(buffer)-1] = ')';
                    buffer[strlen(buffer)] = '\0';
                    fscanf(fptr," ");
                    strcat(cmd,buffer);
                    strcat(cmd," >>index.html 2>/dev/null");
                    break;
                case RSS:
                    strcat(cmd,"./rss ");
                    fscanf(fptr,"[url] => %s ",buffer);
                    if(strcmp(buffer,")")==0)
                        continue;
                    strcat(cmd,"\"");
                    strcat(cmd,buffer);
                    strcat(cmd,"\" ");
                    strcat(cmd,id);
                    strcat(cmd," >/dev/null 2>&1");
                    break;
                }
                strcat(cmd,"\n");
                fscanf(fptr,") ");
                switch(option){
                case '+': // add
                    for(i=0;i<(*line);i++)
                        if(strcmp(content[i],cmd)==0)
                            break;
                    if(i==*line){
                        snprintf(content[(*line)++],MAXLINE,"#ICS task id = %s, comment\n",id);
                        strcpy(content[(*line)++],cmd);
                    }
                    break;
                case '-': // del
                    for(i=1;i<(*line);i++)
                        if(strcmp(content[i],cmd)==0 && content[i-1][0]=='#'){
                            content[i][0] = content[i-1][0] = '\0';
                            break;
                        }
                    break;
                case '!': // modify
                    for(i=1;i<(*line);i++){
                        if(sscanf(content[i],"#ICS task id = %s, comment ",buffer)){
                            buffer[strlen(buffer)-1]='\0';
                            if(strcmp(buffer,id)==0){
                                content[i][0] = content[i+1][0] = '\0';
                                snprintf(content[(*line)++],MAXLINE,"#ICS task id = %s, comment\n",id);
                                strcpy(content[(*line)++],cmd);
                                break;
                            }
                        }
                    }
                    break;
                default:
                    err_quit("unkown option");
                }
                cmd[0] = '\0';
            }
            errno = 0;
            /*fetch*/
            fclose(fptr);
            if(unlink(filename)==-1)
                err_sys();
            //char tmp9[255]="echo rm ";
            //strcat(tmp9, filename);
            //system(tmp9);
            //puts(filename);
        }
        dirp = readdir(dp);
        deal_content(content,line,dp,dirp);
    }
}
Exemple #17
0
void* connection_handler(void* number)
{
	int thread_num = *(int*)number;
	int read_size;
	char client_message[2000];

	getcwd(current_dir[N], 5000);

	printf("[%d] created.\n", thread_num);

	while(!is_working[thread_num]);

	while( (read_size = recv(client_sockets[thread_num] , client_message , 2000 , 0)) > 0 )
	{
		char* command = strtok(client_message, " ");
		printf("[%d] Command: [%s]\n", thread_num, command);
		if (strcmp("LIST", command) == 0)
		{
			char response[10000];

			DIR           *d;
			struct dirent *dir;
			d = opendir(current_dir[thread_num]);
			if (d)
			{
				strcpy(response, "");
				while ((dir = readdir(d)) != NULL)
				{
					
					strcat(response, dir->d_name);
					strcat(response, "\n");
				}

				closedir(d);
			}

			write(client_sockets[thread_num] , response , strlen(response));
		}
		else if (strcmp("CWD", command) == 0)
		{
			char* path = strtok(NULL, " ");
			printf("[%d] Path: [%s]\n", thread_num, path);			
			

			char response[1000];

			struct stat s;
			int err = stat(path, &s);

			if (err != -1 && S_ISDIR(s.st_mode)) // is a dir
			{
				strcpy(current_dir[thread_num], path);
				sprintf(response, "Ok, current_path = %s\n", current_dir[thread_num]);
			}
			else
			{
				sprintf(response, "Wrong path, sorry.\n");
			}

			
			write(client_sockets[thread_num] , response , strlen(response));
		}

		memset(client_message,0,sizeof(client_message));

		
	}

	close(client_sockets[thread_num]);

	printf("[%d] Connection closed.\n", thread_num);

	pthread_create(&tid[thread_num] , NULL , connection_handler , (void*) &thread_num);
	is_working[thread_num] = 0;

	printf("[%d] destroyed.\n", thread_num);
}
Exemple #18
0
int qgrep_main(int argc, char **argv)
{
	int i;
	char *p;
	bool do_eclass;
	bool do_installed;
	DIR *eclass_dir = NULL;
	struct dirent *dentry = NULL;
	int reflags = 0;
	unsigned long int context_optarg;
	char status = 1;
	size_t n;
	char *overlay;

	struct qgrep_grepargs args = {
		.do_count = 0,
		.do_regex = 0,
		.do_list = 0,
		.show_filename = 0,
		.show_name = 0,
		.skip_comments = 0,
		.invert_list = 0,
		.invert_match = 0,
		.skip_pattern = NULL,
		.num_lines_before = 0,
		.num_lines_after = 0,
		.buf_list = NULL,
		.query = NULL,
		.strfunc = strstr,
		.include_atoms = NULL,
		.portdir = NULL,
	};

	do_eclass = do_installed = 0;

	while ((i = GETOPT_LONG(QGREP, qgrep, "")) != -1) {
		switch (i) {
		case 'I': args.invert_match = true;               break;
		case 'i':
			args.strfunc = strcasestr;
			reflags |= REG_ICASE;
			break;
		case 'c': args.do_count = true;                   break;
		case 'l': args.do_list = true;                    break;
		case 'L': args.do_list = args.invert_list = true; break;
		case 'e': args.do_regex = true;                   break;
		case 'x':
			args.do_regex = true;
			reflags |= REG_EXTENDED;
			break;
		case 'J': do_installed = true;                    break;
		case 'E': do_eclass = true;                       break;
		case 'H': args.show_filename = true;              break;
		case 'N': args.show_name = true;                  break;
		case 's': args.skip_comments = true;              break;
		case 'R': args.show_repo = args.show_name = true; break;
		case 'S': args.skip_pattern = optarg;             break;
		case 'B':
		case 'A':
			errno = 0;
			context_optarg = strtol(optarg, &p, 10);
			if (errno != 0)
				errp("%s: not a valid integer", optarg);
			else if (p == optarg || *p != '\0')
				err("%s: not a valid integer", optarg);
			if (context_optarg > 254)
				err("%s: silly value!", optarg);
			if (i == 'B')
				args.num_lines_before = context_optarg;
			else
				args.num_lines_after = context_optarg;
			break;
		COMMON_GETOPTS_CASES(qgrep)
		}
	}
	if (argc == optind)
		qgrep_usage(EXIT_FAILURE);

	if (args.do_list && args.do_count) {
		warn("%s and --count are incompatible options. The former wins.",
				(args.invert_list ? "--invert-list" : "--list"));
		args.do_count = false;
	}

	if (args.show_name && args.show_filename) {
		warn("--with-name and --with-filename are incompatible options. "
				"The former wins.");
		args.show_filename = false;
	}

	if (args.do_list && args.num_lines_before) {
		warn("%s and --before are incompatible options. The former wins.",
				(args.invert_list ? "--invert-list" : "--list"));
		args.num_lines_before = 0;
	}

	if (args.do_list && args.num_lines_after) {
		warn("%s and --after are incompatible options. The former wins.",
				(args.invert_list ? "--invert-list" : "--list"));
		args.num_lines_after = 0;
	}

	if (args.do_count && args.num_lines_before) {
		warn("--count and --before are incompatible options. The former wins.");
		args.num_lines_before = 0;
	}

	if (args.do_count && args.num_lines_after) {
		warn("--count and --after are incompatible options. The former wins.");
		args.num_lines_after = 0;
	}

	if (do_installed && do_eclass) {
		warn("--installed and --eclass are incompatible options. "
				"The former wins.");
		do_eclass = false;
	}

	if (argc > (optind + 1)) {
		depend_atom **d = args.include_atoms =
			xcalloc(sizeof(depend_atom *), (argc - optind - 1) + 1);
		for (i = (optind + 1); i < argc; i++) {
			*d = atom_explode(argv[i]);
			if (*d == NULL) {
				warn("%s: invalid atom, will be ignored", argv[i]);
			} else {
				d++;
			}
		}
		*d = NULL;
	}

	/* make it easier to see what needs to be printed */
	if (!args.show_name && (verbose || args.do_list))
		args.show_filename = true;

	/* pre-compile regexps once for all */
	if (args.do_regex) {
		if (args.invert_match || *RED == '\0')
			reflags |= REG_NOSUB;
		xregcomp(&args.preg, argv[optind], reflags);
		reflags |= REG_NOSUB;
		if (args.skip_pattern)
			xregcomp(&args.skip_preg, args.skip_pattern, reflags);
	}
	args.query = argv[optind];

	/* allocate a circular buffers list for --before */
	args.buf_list = qgrep_buf_list_alloc(args.num_lines_before + 1);

	array_for_each(overlays, n, overlay) {
		args.portdir = overlay;
		if (do_eclass) {
			char buf[_Q_PATH_MAX];
			char name[_Q_PATH_MAX];
			char *label;
			int efd;

			snprintf(buf, sizeof(buf), "%s/%s/eclass", portroot, overlay);
			efd = open(buf, O_RDONLY|O_CLOEXEC);
			if (efd == -1 || (eclass_dir = fdopendir(efd)) == NULL) {
				if (errno != ENOENT)
					warnp("opendir(\"%s/eclass\") failed", overlay);
				continue;
			}
			while ((dentry = readdir(eclass_dir)) != NULL) {
				if (strstr(dentry->d_name, ".eclass") == NULL)
					continue;
				/* filter the files we grep when there are extra args */
				if (args.include_atoms != NULL) {
					depend_atom **d;
					for (d = args.include_atoms; *d != NULL; d++) {
						if ((*d)->PN != NULL && strncmp(dentry->d_name,
									(*d)->PN, strlen((*d)->PN)) == 0)
							break;
					}
					if (*d == NULL)
						continue;
				}

				label = NULL;
				if (args.show_name) {
					snprintf(name, sizeof(name), "%s%.*s%s", BLUE,
							(int)(strlen(dentry->d_name) - 7), dentry->d_name,
							NORM);
					label = name;
				} else if (args.show_filename) {
					snprintf(name, sizeof(name), "eclass/%s", dentry->d_name);
					label = name;
				}
				status = qgrep_grepat(efd, dentry->d_name, label, &args);
			}
			closedir(eclass_dir);
		} else if (do_installed) {
			status = q_vdb_foreach_pkg(portroot, portvdb,
					qgrep_vdb_cb, &args, NULL);
		} else { /* do_ebuild */
			status = cache_foreach_pkg(portroot, overlay,
					qgrep_cache_cb, &args, NULL);
		}
	}

	if (args.do_regex)
		regfree(&args.preg);
	if (args.do_regex && args.skip_pattern)
		regfree(&args.skip_preg);
	if (args.include_atoms != NULL) {
		for (i = 0; i < (argc - optind - 1); i++)
			if (args.include_atoms[i] != NULL)
				atom_implode(args.include_atoms[i]);
		free(args.include_atoms);
	}
	qgrep_buf_list_free(args.buf_list);

	return status;
}
Exemple #19
0
FILE * chooseFile(char* dir)
{
	int files, length;
	getMaxsizeofDIR(dir,&files,&length);
	bool *isDIR = (bool *) malloc(files*sizeof(bool*));
	char **choices = (char**)malloc((files+3)*sizeof(char*));
	int i;
	for(i = 0; i < files; i++)
	{
		choices[i] = (char *)malloc(length*sizeof(char));

	}
	DIR *dp;
	struct dirent *ep;
	dp = opendir (dir);

	if(dp != NULL)
	{

		isDIR[0] = true;
		strcpy(choices[0],"\\..");
		i = 1;
		clearScreen();
		while(!quit)
		{

			if ((ep = readdir (dp))!=NULL)
			{
	
				if(ep->d_name[0]!='.')
				{
					isDIR[i] = ep->d_type==DT_DIR;

					if(isDIR[i])
					{
						strcpy(choices[i],"\\");
						strcat(choices[i],ep->d_name);
					}
					else
						strcpy(choices[i],ep->d_name);
					i++;
				}
			}
			else
			{

				break;
			}
		}
	int result = menus("Select file to be plotted",choices,NULL,files,length+3);
	if(result==-1)
		return NULL;
	char  fileName[1024];
	strcpy(fileName,dir);
	if(result==1)
	{
		char ch = 'a';
		int last = 0;
		int count;
		char fileName2[1024];
		for(count = 0;ch !='\0';count++)
		{
			ch = fileName[count];
			if(ch=='/'&&fileName[count+1]!='\0')
				last = count;
		}
		last++;
		for(count = 0;count < last;count++)
		{
			fileName2[count] = fileName[count];
		}
		fileName2[last] = '\0';
		return chooseFile(fileName2);
	
	}
	int loop;
	char c = 'a';
	strcat(fileName,"\0");
	for(loop = 0;c !='\0';loop++)
	{
		 c = fileName[loop];
	}
	if(loop>2&&fileName[loop-2]!='/')	
		strcat(fileName,"/");

	if(isDIR[result-1])
	{

		strcat(fileName,&(choices[result-1][1]));
		return chooseFile(fileName);
	}
		strcat(fileName,choices[result-1]);
	}
	else
	{
		printw("\ngot an error could not open the directory!\n");
		getch();
		perror("Could't open the directory");
	}
		return fopen("makefile","r"); 

}
/* lnstat_scan_dir - find and parse all available statistics files/fields */
struct lnstat_file *lnstat_scan_dir(const char *path, const int num_req_files,
				    const char **req_files)
{
	DIR *dir;
	struct lnstat_file *lnstat_files = NULL;
	struct dirent *de;

	if (!path)
		path = PROC_NET_STAT;

	dir = opendir(path);
	if (!dir) {
		struct lnstat_file *lf;
		/* Old kernel, before /proc/net/stat was introduced */
		fprintf(stderr, "Your kernel doesn't have lnstat support. ");

		/* we only support rtstat, not multiple files */
		if (num_req_files >= 2) {
			fputc('\n', stderr);
			return NULL;
		}

		/* we really only accept rt_cache */
		if (num_req_files && !name_in_array(num_req_files,
						    req_files, "rt_cache")) {
			fputc('\n', stderr);
			return NULL;
		}

		fprintf(stderr, "Fallback to old rtstat-only operation\n");

		lf = alloc_and_open("/proc/net", "rt_cache_stat");
		if (!lf)
			return NULL;
		lf->compat = 1;
		strncpy(lf->basename, "rt_cache", sizeof(lf->basename));

		/* FIXME: support for old files */
		if (lnstat_scan_compat_rtstat_fields(lf) < 0)
			return NULL;

		lf->next = lnstat_files;
		lnstat_files = lf;
		return lnstat_files;
	}

	while ((de = readdir(dir))) {
		struct lnstat_file *lf;

		if (de->d_type != DT_REG)
			continue;

		if (num_req_files && !name_in_array(num_req_files,
						    req_files, de->d_name))
			continue;

		lf = alloc_and_open(path, de->d_name);
		if (!lf)
			return NULL;

		/* fill in field structure */
		if (lnstat_scan_fields(lf) < 0)
			return NULL;

		/* prepend to global list */
		lf->next = lnstat_files;
		lnstat_files = lf;
	}
	closedir(dir);

	return lnstat_files;
}
Exemple #21
0
//Solaris and AIX should have this
DWORD
CTGetPidOfCmdLine(
    PCSTR programName,
    PCSTR programFilename,
    PCSTR cmdLine,
    uid_t owner,
    pid_t *pid,
    size_t *count
    )
{
    DWORD ceError = ERROR_NOT_SUPPORTED;
    size_t fillCount = 0;
    size_t foundCount = 0;
    struct stat findStat;
    DIR *dir = NULL;
    struct dirent *dirEntry = NULL;
    PSTR filePath = NULL;
    struct psinfo infoStruct;
    FILE *infoFile = NULL;
    struct stat compareStat;
    BOOLEAN bFileExists;
#if defined(__LWI_SOLARIS__)
    int (*getzoneid)() = NULL;
    int zoneid = -1;
#endif

    if(count)
    {
        fillCount = *count;
        *count = 0;
    }
    else if(pid != NULL)
        fillCount = 1;

    if(programFilename != NULL)
    {
        while(stat(programFilename, &findStat) < 0)
        {
            if(errno == EINTR)
                continue;
            GCE(ceError = LwMapErrnoToLwError(errno));
        }
    }

    if ((dir = opendir("/proc")) == NULL) {
        GCE(ceError = LwMapErrnoToLwError(errno));
    }

#if defined(__LWI_SOLARIS__)
    getzoneid = dlsym(RTLD_DEFAULT, "getzoneid");
    if (getzoneid)
    {
        zoneid = getzoneid();
    }
#endif

    while(1)
    {
        errno = 0;
        dirEntry = readdir(dir);
        if(dirEntry == NULL)
        {
            if(errno != 0)
                GCE(ceError = LwMapErrnoToLwError(errno));
            else
            {
                //No error here. We simply read the last entry
                break;
            }
        }
        if(dirEntry->d_name[0] == '.')
            continue;
        // On AIX, there is a /proc/sys which does not contain a psinfo
        if(!isdigit((int)dirEntry->d_name[0]))
            continue;
        CT_SAFE_FREE_STRING(filePath);
        GCE(ceError = CTAllocateStringPrintf(&filePath, "/proc/%s/psinfo",
                    dirEntry->d_name));
        GCE(ceError = CTCheckFileOrLinkExists(filePath, &bFileExists));
        if(!bFileExists)
        {
            // On AIX 6.1, a defunct process can lack a psinfo file.
            continue;
        }
        GCE(ceError = CTSafeCloseFile(&infoFile));
        GCE(ceError = CTOpenFile(filePath, "r", &infoFile));
        if(fread(&infoStruct, sizeof(infoStruct), 1, infoFile) != 1)
        {
            GCE(ceError = LwMapErrnoToLwError(errno));
        }

#if defined(__LWI_SOLARIS__)
        if (zoneid != -1)
        {
            int processzoneid = -1;

#ifdef HAVE_STRUCT_PSINFO_PR_ZONEID
            processzoneid = (int) infoStruct.pr_zoneid;
#else
            processzoneid = (int)
                *(infoStruct.pr_filler +
                sizeof(infoStruct.pr_filler)/sizeof(infoStruct.pr_filler[0]) -
                3);
#endif
            if (zoneid != processzoneid)
            {
                continue;
            }
        }
#endif

        if (owner != (uid_t)-1 && owner != infoStruct.pr_euid)
        {
            continue;
        }
        if (programName != NULL && strcmp(infoStruct.pr_fname, programName))
        {
            continue;
        }
        if (cmdLine != NULL && strcmp(infoStruct.pr_psargs, cmdLine))
        {
            continue;
        }
        if(programFilename != NULL)
        {
            CT_SAFE_FREE_STRING(filePath);
            GCE(ceError = CTAllocateStringPrintf(&filePath,
                        "/proc/%s/object/a.out",
                        dirEntry->d_name));

            while(stat(filePath, &compareStat) < 0)
            {
                if(errno == EINTR)
                    continue;
                if(errno == ENOENT || errno == ENOTDIR)
                {
                    //This process wasn't executed from a file?
                    goto not_match;
                }
                GCE(ceError = LwMapErrnoToLwError(errno));
            }
            if(findStat.st_ino != compareStat.st_ino)
                continue;
            if(findStat.st_dev != compareStat.st_dev)
                continue;
            if(findStat.st_rdev != compareStat.st_rdev)
                continue;
        }
 
        //This is a match
        if(foundCount < fillCount)
            pid[foundCount] = infoStruct.pr_pid;
        foundCount++;
not_match:
        ;
    }

    if(count)
        *count = foundCount;
    else if(!ceError && foundCount == 0)
        ceError = ERROR_PROC_NOT_FOUND;

cleanup:
    if(dir != NULL)
        closedir(dir);
    CT_SAFE_FREE_STRING(filePath);
    CTSafeCloseFile(&infoFile);

    return ceError;
}
Exemple #22
0
csFILE *CS_fopen(const char *filename, const char *mode)
{
	extern char cs_DirsepC;
	struct stat statbuf;
	csFILE *result = NULL;
	char *fixed_filename = (char*) filename;

	/* If we are attempting to read from the file, and the file passed
	 * in does not exist, look for a different file in the same directory
	 * that has the same filename with a different case.
	 */

	if ( (*mode == *_STRM_TXTRD) && stat(filename,&statbuf) )
	{
		/* Make a copy of the filename passed in, and separate it into
		 * directory and path components.
		 */

		char *last_path_sep;

		fixed_filename = (char*) malloc(strlen(filename)+1);
		strcpy(fixed_filename,filename);
		last_path_sep = strrchr(fixed_filename,cs_DirsepC);
		if ( last_path_sep )
		{
			/* Unless the directory is the current directory, we'd
			 * better make sure that at least the directory exists!
			 */
			char *filename_part = last_path_sep + 1;
			*last_path_sep = '\0';
			if ( ! stat(fixed_filename,&statbuf) )
			{
				/* Search the contents of the directory for a file which
				 * matches the one passed in, allowing for different
				 * case.
				 */
#if 1
				DIR *directory = opendir(fixed_filename);
				if ( directory )
				{
					struct dirent *entry;
					while ( (entry = readdir(directory)) != 0 )
					{
						if ( ! CS_stricmp(entry->d_name,filename_part) )
						{
							 /* We have a match!  It should be safe to assume that
							  * their lengths are the same, so we'll just copy it
							  * in-place.
							  */
							strcpy(filename_part,entry->d_name);
							break;
						}
					}
					closedir(directory);
				}
#else
				struct dirent *name_list = NULL;
				int num_matches = scandir( fixed_filename, name_list, NULL, NULL);
				if (num_matches > 0)
				{
					int ii;
					for (ii=0;ii < num_matches;ii++ )
					{
						if (!CS_stricmp (name_list[ii].d_name,filename_part))
						{
							 /* We have a match!  It should be safe to assume that
							  * their lengths are the same, so we'll just copy it
							  * in-place.
							  */
							strcpy (filename_part,name_list[ii].d_name);
							break;
						}
					}
					free (name_list);
				}
#endif
				/* Replace the directory/path separator */
				*last_path_sep = cs_DirsepC;
			}
		}
	}
	result = (csFILE*) fopen(fixed_filename,mode);
	if ( filename != fixed_filename )
	{
		free(fixed_filename);
	}
	return result;
}
Exemple #23
0
int main(int argc, char *argv[])
{
	int warning_displayed = 0;
	int c;
	int daemonize = 0;

	if (os_program_init())
		return -1;

	for (;;) {
		c = getopt(argc, argv, "a:BhG:i:p:P:s:v");
		if (c < 0)
			break;
		switch (c) {
		case 'a':
			action_file = optarg;
			break;
		case 'B':
			daemonize = 1;
			break;
		case 'G':
			ping_interval = atoi(optarg);
			break;
		case 'h':
			usage();
			return 0;
		case 'v':
			printf("%s\n", hostapd_cli_version);
			return 0;
		case 'i':
			os_free(ctrl_ifname);
			ctrl_ifname = os_strdup(optarg);
			break;
		case 'p':
			ctrl_iface_dir = optarg;
			break;
		case 'P':
			pid_file = optarg;
			break;
		case 's':
			client_socket_dir = optarg;
			break;
		default:
			usage();
			return -1;
		}
	}

	interactive = (argc == optind) && (action_file == NULL);

	if (interactive) {
		printf("%s\n\n%s\n\n", hostapd_cli_version, cli_license);
	}

	if (eloop_init())
		return -1;

	for (;;) {
		if (ctrl_ifname == NULL) {
			struct dirent *dent;
			DIR *dir = opendir(ctrl_iface_dir);
			if (dir) {
				while ((dent = readdir(dir))) {
					if (os_strcmp(dent->d_name, ".") == 0
					    ||
					    os_strcmp(dent->d_name, "..") == 0)
						continue;
					printf("Selected interface '%s'\n",
					       dent->d_name);
					ctrl_ifname = os_strdup(dent->d_name);
					break;
				}
				closedir(dir);
			}
		}
		ctrl_conn = hostapd_cli_open_connection(ctrl_ifname);
		if (ctrl_conn) {
			if (warning_displayed)
				printf("Connection established.\n");
			break;
		}

		if (!interactive) {
			perror("Failed to connect to hostapd - "
			       "wpa_ctrl_open");
			return -1;
		}

		if (!warning_displayed) {
			printf("Could not connect to hostapd - re-trying\n");
			warning_displayed = 1;
		}
		os_sleep(1, 0);
		continue;
	}

	if (interactive || action_file) {
		if (wpa_ctrl_attach(ctrl_conn) == 0) {
			hostapd_cli_attached = 1;
			register_event_handler(ctrl_conn);
		} else {
			printf("Warning: Failed to attach to hostapd.\n");
			if (action_file)
				return -1;
		}
	}

	if (daemonize && os_daemonize(pid_file) && eloop_sock_requeue())
		return -1;

	if (interactive)
		hostapd_cli_interactive();
	else if (action_file)
		hostapd_cli_action(ctrl_conn);
	else
		wpa_request(ctrl_conn, argc - optind, &argv[optind]);

	unregister_event_handler(ctrl_conn);
	os_free(ctrl_ifname);
	eloop_destroy();
	hostapd_cli_cleanup();
	return 0;
}
Exemple #24
0
void
addfdsns_to_list (TDSNCHOOSER *dsnchoose_t, char *path, Boolean b_reset)
{
  DataBrowserItemID item = DBITEM_ID + 1;
  DataBrowserCallbacks dbCallbacks;
  ThemeDrawingState outState = NULL;
  UInt16 colSize[3] = { 400, 100, 150 };
  SInt16 outBaseline;
  Point ioBound;
  int i;
  DIR *dir;
  char *path_buf;
  struct dirent *dir_entry;
  struct stat fstat;
  int b_added;
  ControlRef widget;
  WindowRef dlg;

  if (!dsnchoose_t || !path)
    return; 

  widget = dsnchoose_t->fdsnlist;
  dlg = dsnchoose_t->mainwnd;

  GetThemeDrawingState (&outState);

  /* Install an event handler on the component databrowser */
  dbCallbacks.version = kDataBrowserLatestCallbacks;
  InitDataBrowserCallbacks (&dbCallbacks);
  dbCallbacks.u.v1.itemNotificationCallback =
      NewDataBrowserItemNotificationUPP (fdsn_notification_item);
  /* On Mac OS X 10.0.x : clientDataCallback */
  dbCallbacks.u.v1.itemDataCallback =
      NewDataBrowserItemDataUPP (fdsn_getset_item);
  SetDataBrowserCallbacks (widget, &dbCallbacks);
  /* Begin the draw of the data browser */
  SetDataBrowserTarget (widget, DBITEM_ID);

  /* Make the clean up */
  for (i = 0; i < FDSN_nrows; i++, item++)
    {
      CFRelease (FDSN_array[i]);
      FDSN_array[i] = NULL;
      FDSN_type[i] = 0;
      RemoveDataBrowserItems (widget, DBITEM_ID, 1, &item, DBNAME_ID);
    }

  ActivateControl (widget);
  DrawOneControl (widget);

  /* Global Initialization */
  FDSN_nrows = 0;
  item = DBITEM_ID + 1;

  if ((dir = opendir (path)))
    {
      while ((dir_entry = readdir (dir)) && FDSN_nrows < MAX_ROWS)
	{
	  asprintf (&path_buf, "%s/%s", path, dir_entry->d_name);
	  b_added = 0;

	  if (stat ((LPCSTR) path_buf, &fstat) >= 0 && S_ISDIR (fstat.st_mode))
	    {
	      if (dir_entry->d_name && dir_entry->d_name[0] != '.') 
	        {
                  FDSN_array[FDSN_nrows] = CFStringCreateWithCString(NULL, dir_entry->d_name, kCFStringEncodingUTF8);
                  FDSN_type[FDSN_nrows] = 0;
                  b_added = 1;
	        }
	    }
	  else if (stat ((LPCSTR) path_buf, &fstat) >= 0 && !S_ISDIR (fstat.st_mode)
	           && strstr (dir_entry->d_name, ".dsn"))
	    {
              FDSN_array[FDSN_nrows] = CFStringCreateWithCString(NULL, dir_entry->d_name, kCFStringEncodingUTF8);
              FDSN_type[FDSN_nrows] = 1;
              b_added = 1;
	    }

	  if (path_buf)
	    free (path_buf);

	  if (b_added)
	    {
              GetThemeTextDimensions (FDSN_array[FDSN_nrows], kThemeSystemFont,
                kThemeStateActive, false, &ioBound, &outBaseline);
              if(colSize[0] < ioBound.h) colSize[0] = ioBound.h;

              AddDataBrowserItems (widget, DBITEM_ID, 1, &item, DBNAME_ID);
              item++;
              FDSN_nrows++;
            }
	}

      /* Close the directory entry */
      closedir (dir);
    }
  else
    create_error (NULL, NULL, "Error during accessing directory information",
	strerror (errno));

  ActivateControl (widget);
  /* Resize the columns to have a good look */
  SetDataBrowserTableViewNamedColumnWidth (widget, DBNAME_ID, colSize[0] + 20);
  DrawOneControl (widget);
  /* Remove the DataBrowser callback */
  SetDataBrowserCallbacks (NULL, &dbCallbacks);
  if(outState) DisposeThemeDrawingState (outState);

  if (b_reset)
    SetDataBrowserScrollPosition(widget, 0, 0);

  fill_dir_menu(dsnchoose_t, path);
}
static ngx_int_t
ngx_http_dav_ext_send_propfind(ngx_http_request_t *r)
{
	size_t                    root;
	ngx_str_t                 path, spath, suri;
	ngx_chain_t               *l = NULL, **ll = &l;
	DIR                       *dir;
	int                       depth;
	struct dirent             *de;
	size_t                    len;
	ngx_http_variable_value_t vv;
	ngx_str_t                 depth_name = ngx_string("depth");
	u_char                    *p;

	if (ngx_http_variable_unknown_header(&vv, &depth_name, 
					&r->headers_in.headers.part, 0) == NGX_OK
		&& vv.valid)
	{
		if (vv.len == sizeof("infinity") -1 
			&& !ngx_strncasecmp(vv.data, (u_char*)"infinity", vv.len))
		{
			depth = DAV_EXT_INFINITY; 
		} else {
			depth = ngx_atoi(vv.data, vv.len);
		}

	} else {
		depth = DAV_EXT_INFINITY;
	}

	p = ngx_http_map_uri_to_path(r, &path, &root, 0);

	if (p == NULL || !path.len) {

		ngx_log_error(NGX_LOG_ALERT, r->connection->log, 0,
				"dav_ext error mapping uri to path");

		return NGX_ERROR;
	}

	path.len = p - path.data;
	*p = 0;

	ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
			"http propfind path: \"%V\"", &path);

	NGX_HTTP_DAV_EXT_OUTL(
		"<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n"
		"<D:multistatus xmlns:D=\"DAV:\">\n"
		);

	ngx_http_dav_ext_flush(r, ll);

	ngx_http_dav_ext_send_propfind_item(r, (char*)path.data, &r->uri);

	if (depth) {

		/* treat infinite depth as 1 for performance reasons */

		if ((dir = opendir((char*)path.data))) {

			while((de = readdir(dir))) {

				if (!strcmp(de->d_name, ".")
					|| !strcmp(de->d_name, ".."))
				{
					continue;
				}

				len = strlen(de->d_name);

				ngx_http_dav_ext_make_child(r->pool, &path, 
					(u_char*)de->d_name, len, &spath);

				ngx_http_dav_ext_make_child(r->pool, &r->uri, 
					(u_char*)de->d_name, len, &suri);

				ngx_http_dav_ext_send_propfind_item(r, (char*)spath.data, &suri);

			}

			closedir(dir);
		}

	}

	NGX_HTTP_DAV_EXT_OUTL(
		"</D:multistatus>\n"
		);

	if (*ll && (*ll)->buf) {
		(*ll)->buf->last_buf = 1;
	}

	ngx_http_dav_ext_flush(r, ll);

	return NGX_OK;
}
int main() {
	std::setlocale(LC_ALL, "de_DE.UTF-8"); // important for utf-8 multibyte chars
	const std::string path = "/home/typology/1/";
	const std::string path2 = "/home/typology/1sorted/";
	 struct dirent *entry;
	  DIR *dp;

	  dp = opendir(path.c_str());
	  if (dp == NULL) {
	    std::cout << "Path \"" << path << "\" does not exist or could not be read." << std::endl;
	    return 1;
	  }

	  std::string source;
	  std::string target;
	  float score;
	  std::vector<std::string> vSource;
	  std::vector<std::string> vTarget;
	  std::vector<float> vScore;
	  std::tuple<int,char> foo;
	  std::vector<std::tuple<std::string,std::string,float>>* vt = new std::vector<std::tuple<std::string,std::string,float>>();
	  std::vector<std::string> filenames;

	  while ((entry = readdir(dp))){
		if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
			continue;
		}
		filenames.push_back(entry->d_name);
	  }
	  closedir(dp);
	  std::sort(filenames.begin(), filenames.end());
	  wchar_t lastChar;
	  wchar_t currentChar;
	  std::string lastfName;

	  mbrtowc(&lastChar, &filenames[0][0], MB_CUR_MAX, NULL); // Convert multibyte sequence (utf-8) to wide character
	  lastfName = filenames[0];
	  for(auto iter = filenames.begin(); iter != filenames.end(); ++iter) {
		  mbrtowc(&currentChar, &((*iter)[0]), 4, NULL);
		  		if(currentChar != lastChar) {
		  			std::sort(vt->begin(),vt->end(),&compareTwoRows);
		  			std::ofstream myfile ((path2 + lastfName).c_str() );
		  			if (myfile.is_open())
		  			{
		  				for (auto i : *vt){
		  					myfile << std::get<0>(i) << '\t' << std::get<1>(i) << '\t' << std::get<2>(i) << '\n';
		  				}
		  			  myfile.close();
		  			}
		  			vt->clear();
		  			lastChar = currentChar;
		  			lastfName = *iter;
		  		}
	    std::ifstream file((path + *iter).c_str());
	    std::cout << "reading file : " << path + *iter << std::endl;
	    for(std::string line; getline(file, line);) {
			std::istringstream ss(line);
			ss >> source >> target;
			ss.ignore(2);
			ss >> score;
			vt->push_back(std::make_tuple (source, target, score));
	    }

  		if(iter == filenames.end() - 1) {
  			std::sort(vt->begin(),vt->end(),&compareTwoRows);
  			std::ofstream myfile ((path2 + lastfName).c_str() );
  			if (myfile.is_open())
  			{
  				for (auto i : *vt){
  					myfile << std::get<0>(i) << '\t' << std::get<1>(i) << '\t' << std::get<2>(i) << '\n';
  				}
  			  myfile.close();
  			}
  		}
	  }
	  delete vt;
	  return 0;
}
Exemple #27
0
int ls(char *path) {
    int result = 0;
    printf("Content-Type: text/html; charset=utf-8\n\n<html><head><title>%s</title><style type=\"text/css\">"
            " .K { color:green; }"
            " .M { color:orange; }"
            " .G { color:red; }"
            " td.size { text-align:right; }"
            "</style></head><body>%s<br>",path,path);
    DIR *d = opendir(path);
    if (d) {
        Array *dirs = array_new(free);
        Array *files = array_new(free);
        struct dirent *f ;
        while((f = readdir(d)) != NULL) {
            
            char *p,*u;
            double size=0;
            char *unit="b";
            int precision=0;
            char *size_str=NULL;
            struct STAT64 st;

            ovs_asprintf(&p,"%s/%s",path,f->d_name);
            //printf("<br>checking %s\n",p);
            //u = file_to_url(p);

            ovs_asprintf(&u,"?%s",p);

            util_stat(p,&st);

            size = st.st_size;
            if (f->d_type == 0) {
                // more nmt100 oddness - dirent type not set?
                if (S_ISREG(st.st_mode)) f->d_type = DT_REG;
                else if (S_ISDIR(st.st_mode)) f->d_type = DT_DIR;
            }
            if (size > 1024 ) { size /= 1024 ; unit="<span class=\"K\">K</span>" ; precision=1; }
            if (size > 1024 ) { size /= 1024 ; unit="<font class=\"M\">M</span>" ; }
            if (size > 1024 ) { size /= 1024 ; unit="<span class=\"G\">G</span>" ; }

            char *display = f->d_name;
            if (strcmp(f->d_name,"..") == 0) {
                // find parent folder name
                char *tmp = STRDUP(path);
                ovs_asprintf(&u,"?%s",dirname(tmp));
                FREE(tmp);
                display="up↑";  ; // UP
            }

            if (strcmp(f->d_name,".") != 0) {
                char *tmp;
                switch(f->d_type) {
                    case DT_REG:
                        if(strstr(f->d_name,"log.gz")) {
                            // Display inline link
                            ovs_asprintf(&tmp,"<tr><td><a href=\"%s.txt\">%s</a> <a href=\"%s\">*</a></td><td class=\"size\"> - %.*f%s</td></tr>",
                                    u,display,u, precision,size,unit);
                        } else {
                            //ovs_asprintf(&tmp,"<tr><td>%.1f%s</td><td><a href=\"%s\">%s</a></td></tr>",size,unit,u,f->d_name);
                            ovs_asprintf(&tmp,"<tr><td><a href=\"%s\">%s</a></td><td class=\"size\"> - %.*f%s</td></tr>",
                                    u,display, precision,size,unit);
                        }
                        array_add(files,tmp);
                        break;
                    case DT_DIR:
                        ovs_asprintf(&tmp,"<a href=\"%s\">%s</a>&nbsp;&nbsp;&nbsp;&nbsp; ",u,display);
                        array_add(dirs,tmp);
                        break;
                    default:
                        ovs_asprintf(&tmp,"<tr><td><a href=\"%s\">%s</a></td><td>%d?</td></tr>",u,f->d_name,f->d_type);
                        array_add(files,tmp);
                        break;
                }
            }
            FREE(size_str);
            FREE(u);
            FREE(p);
        }

        closedir(d);

        char *out;
        array_sort(dirs,NULL);
        out = arraystr(dirs);
        if (out) {
            printf("%s",out);
        }
        FREE(out);

        printf("<hr><table border=\"0\">");
        array_sort(files,NULL);
        out = arraystr(files);
        if (out) {
            printf("%s",out);
        }
        FREE(out);
        printf("</table>");

        array_free(dirs);
        array_free(files);
    } else {
        fprintf(stderr,"Error %d opening [%s]\n",errno,path);
        result = errno;
    }
    printf("</body></html>");
    return result;
}
Exemple #28
0
/*
 * Handle a "special request"
 */
static errr Term_xtra_gcu(int n, int v)
{
	term_data *td = (term_data *)(Term->data);

	/* Analyze the request */
	switch (n)
	{
		/* Clear screen */
	case TERM_XTRA_CLEAR:
		touchwin(td->win);
		(void)wclear(td->win);
		return (0);

		/* Make a noise */
	case TERM_XTRA_NOISE:
		(void)write(1, "\007", 1);
		return (0);

		/* Flush the Curses buffer */
	case TERM_XTRA_FRESH:
		(void)wrefresh(td->win);
		return (0);

#ifdef USE_CURS_SET

		/* Change the cursor visibility */
	case TERM_XTRA_SHAPE:
		curs_set(v);
		return (0);

#endif

		/* Suspend/Resume curses */
	case TERM_XTRA_ALIVE:
		return (Term_xtra_gcu_alive(v));

		/* Process events */
	case TERM_XTRA_EVENT:
		return (Term_xtra_gcu_event(v));

		/* Flush events */
	case TERM_XTRA_FLUSH:
		while (!Term_xtra_gcu_event(FALSE));
		return (0);

		/* Delay */
	case TERM_XTRA_DELAY:
		usleep(1000 * v);
		return (0);

		/* Get Delay of some milliseconds */
	case TERM_XTRA_GET_DELAY:
		{
			int ret;
			struct timeval tv;

			ret = gettimeofday(&tv, NULL);
			Term_xtra_long = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);

			return ret;
		}

		/* Subdirectory scan */
	case TERM_XTRA_SCANSUBDIR:
		{
			DIR *directory;
			struct dirent *entry;

			scansubdir_max = 0;

			directory = opendir(scansubdir_dir);
			if (!directory)
				return 1;

			while ((entry = readdir(directory)))
			{
				char file[PATH_MAX + NAME_MAX + 2];
				struct stat filedata;

				file[PATH_MAX + NAME_MAX] = 0;
				strncpy(file, scansubdir_dir, PATH_MAX);
				strncat(file, "/", 2);
				strncat(file, entry->d_name, NAME_MAX);
				if (!stat(file, &filedata) && S_ISDIR((filedata.st_mode)))
				{
					string_free(scansubdir_result[scansubdir_max]);
					scansubdir_result[scansubdir_max] = string_make(entry->d_name);
					++scansubdir_max;
				}
			}
		}

		/* React to events */
	case TERM_XTRA_REACT:
		Term_xtra_gcu_react();
		return (0);
	}

	/* Unknown */
	return (1);
}
/*
 * _get_process_data() - Build a table of all current processes
 *
 * IN:	pid.
 *
 * OUT:	none
 *
 * THREADSAFE! Only one thread ever gets here.
 *
 * Assumption:
 *    Any file with a name of the form "/proc/[0-9]+/stat"
 *    is a Linux-style stat entry. We disregard the data if they look
 *    wrong.
 */
static void _get_process_data(void)
{
	static	int	slash_proc_open = 0;

	struct	dirent *slash_proc_entry;
	char		*iptr = NULL, *optr = NULL;
	FILE		*stat_fp = NULL;
	char		proc_stat_file[256];	/* Allow ~20x extra length */
	List prec_list = NULL;
	pid_t *pids = NULL;
	int npids = 0;
	uint32_t total_job_mem = 0, total_job_vsize = 0;
	int		i, fd;
	ListIterator itr;
	ListIterator itr2;
	prec_t *prec = NULL;
	struct jobacctinfo *jobacct = NULL;
	static int processing = 0;
	long		hertz;

	if (!pgid_plugin && (cont_id == (uint64_t)NO_VAL)) {
		debug("cont_id hasn't been set yet not running poll");
		return;
	}

	if(processing) {
		debug("already running, returning");
		return;
	}
	processing = 1;
	prec_list = list_create(_destroy_prec);

	hertz = sysconf(_SC_CLK_TCK);
	if (hertz < 1) {
		error ("_get_process_data: unable to get clock rate");
		hertz = 100;	/* default on many systems */
	}

	if(!pgid_plugin) {
		/* get only the processes in the proctrack container */
		slurm_container_get_pids(cont_id, &pids, &npids);
		if(!npids) {
			debug4("no pids in this container %"PRIu64"", cont_id);
			goto finished;
		}
		for (i = 0; i < npids; i++) {
			snprintf(proc_stat_file, 256,
				 "/proc/%d/stat", pids[i]);
			if ((stat_fp = fopen(proc_stat_file, "r"))==NULL)
				continue;  /* Assume the process went away */
			/*
			 * Close the file on exec() of user tasks.
			 *
			 * NOTE: If we fork() slurmstepd after the
			 * fopen() above and before the fcntl() below,
			 * then the user task may have this extra file
			 * open, which can cause problems for
			 * checkpoint/restart, but this should be a very rare
			 * problem in practice.
			 */
			fd = fileno(stat_fp);
			fcntl(fd, F_SETFD, FD_CLOEXEC);

			prec = xmalloc(sizeof(prec_t));
			if (_get_process_data_line(fd, prec))
				list_append(prec_list, prec);
			else
				xfree(prec);
			fclose(stat_fp);
		}
	} else {
		slurm_mutex_lock(&reading_mutex);

		if (slash_proc_open) {
			rewinddir(slash_proc);
		} else {
			slash_proc=opendir("/proc");
			if (slash_proc == NULL) {
				perror("opening /proc");
				slurm_mutex_unlock(&reading_mutex);
				goto finished;
			}
			slash_proc_open=1;
		}
		strcpy(proc_stat_file, "/proc/");

		while ((slash_proc_entry = readdir(slash_proc))) {

			/* Save a few cyles by simulating
			   strcat(statFileName, slash_proc_entry->d_name);
			   strcat(statFileName, "/stat");
			   while checking for a numeric filename (which really
			   should be a pid).
			*/
			optr = proc_stat_file + sizeof("/proc");
			iptr = slash_proc_entry->d_name;
			i = 0;
			do {
				if((*iptr < '0')
				   || ((*optr++ = *iptr++) > '9')) {
					i = -1;
					break;
				}
			} while (*iptr);

			if(i == -1)
				continue;
			iptr = (char*)"/stat";

			do {
				*optr++ = *iptr++;
			} while (*iptr);
			*optr = 0;

			if ((stat_fp = fopen(proc_stat_file,"r"))==NULL)
				continue;  /* Assume the process went away */
			/*
			 * Close the file on exec() of user tasks.
			 *
			 * NOTE: If we fork() slurmstepd after the
			 * fopen() above and before the fcntl() below,
			 * then the user task may have this extra file
			 * open, which can cause problems for
			 * checkpoint/restart, but this should be a very rare
			 * problem in practice.
			 */
			fd = fileno(stat_fp);
			fcntl(fd, F_SETFD, FD_CLOEXEC);

			prec = xmalloc(sizeof(prec_t));
			if (_get_process_data_line(fd, prec))
				list_append(prec_list, prec);
			else
				xfree(prec);
			fclose(stat_fp);
		}
		slurm_mutex_unlock(&reading_mutex);

	}

	if (!list_count(prec_list)) {
		goto finished;	/* We have no business being here! */
	}

	slurm_mutex_lock(&jobacct_lock);
	if(!task_list || !list_count(task_list)) {
		slurm_mutex_unlock(&jobacct_lock);
		goto finished;
	}

	itr = list_iterator_create(task_list);
	while((jobacct = list_next(itr))) {
		itr2 = list_iterator_create(prec_list);
		while((prec = list_next(itr2))) {
			if (prec->pid == jobacct->pid) {
#if _DEBUG
				info("pid:%u ppid:%u rss:%d KB",
				     prec->pid, prec->ppid, prec->rss);
#endif
				/* find all my descendents */
				_get_offspring_data(prec_list,
						    prec, prec->pid);
				/* tally their usage */
				jobacct->max_rss = jobacct->tot_rss =
					MAX(jobacct->max_rss, prec->rss);
				total_job_mem += prec->rss;
				jobacct->max_vsize = jobacct->tot_vsize =
					MAX(jobacct->max_vsize, prec->vsize);
				total_job_vsize += prec->vsize;
				jobacct->max_pages = jobacct->tot_pages =
					MAX(jobacct->max_pages, prec->pages);
				jobacct->min_cpu = jobacct->tot_cpu =
					MAX(jobacct->min_cpu,
					    (prec->ssec / hertz +
					     prec->usec / hertz));
				debug2("%d mem size %u %u time %u(%u+%u)",
				       jobacct->pid, jobacct->max_rss,
				       jobacct->max_vsize, jobacct->tot_cpu,
				       prec->usec, prec->ssec);
				break;
			}
		}
		list_iterator_destroy(itr2);
	}
	list_iterator_destroy(itr);
	slurm_mutex_unlock(&jobacct_lock);

	if (jobacct_mem_limit) {
		if (jobacct_step_id == NO_VAL) {
			debug("Job %u memory used:%u limit:%u KB",
			      jobacct_job_id, total_job_mem, jobacct_mem_limit);
		} else {
			debug("Step %u.%u memory used:%u limit:%u KB",
			      jobacct_job_id, jobacct_step_id,
			      total_job_mem, jobacct_mem_limit);
		}
	}
	if (jobacct_job_id && jobacct_mem_limit &&
	    (total_job_mem > jobacct_mem_limit)) {
		if (jobacct_step_id == NO_VAL) {
			error("Job %u exceeded %u KB memory limit, being "
			      "killed", jobacct_job_id, jobacct_mem_limit);
		} else {
			error("Step %u.%u exceeded %u KB memory limit, being "
			      "killed", jobacct_job_id, jobacct_step_id,
			      jobacct_mem_limit);
		}
		_acct_kill_step();
	} else if (jobacct_job_id && jobacct_vmem_limit &&
	           (total_job_vsize > jobacct_vmem_limit)) {
		if (jobacct_step_id == NO_VAL) {
			error("Job %u exceeded %u KB virtual memory limit, "
			      "being killed", jobacct_job_id,
			      jobacct_vmem_limit);
		} else {
			error("Step %u.%u exceeded %u KB virtual memory "
			      "limit, being killed", jobacct_job_id,
			      jobacct_step_id, jobacct_vmem_limit);
		}
		_acct_kill_step();
	}

finished:
	list_destroy(prec_list);
	processing = 0;
	return;
}
Exemple #30
0
int __getcwd(char *path, size_t size)
{
    struct stat above, current, tmp;
    struct dirent *entry;
    DIR *d;
    char *p, *up, *dotdot;
    int cycle;

    if (path == NULL || size <= 1) {
        errno= EINVAL;
        return -1;
    }

    p= path + size;
    *--p = 0;

    if (stat(".", &current) < 0) return -1;

    while (1) {
        dotdot= "..";
        if (stat(dotdot, &above) < 0) {
            recover(p);
            return -1;
        }

        if (above.st_dev == current.st_dev
                && above.st_ino == current.st_ino)
            break;	/* Root dir found */

        if ((d= opendir(dotdot)) == NULL) {
            recover(p);
            return -1;
        }

        /* Cycle is 0 for a simple inode nr search, or 1 for a search
         * for inode *and* device nr.
         */
        cycle= above.st_dev == current.st_dev ? 0 : 1;

        do {
            char name[3 + NAME_MAX + 1];

            tmp.st_ino= 0;
            if ((entry= readdir(d)) == NULL) {
                switch (++cycle) {
                case 1:
                    rewinddir(d);
                    continue;
                case 2:
                    closedir(d);
                    errno= ENOENT;
                    recover(p);
                    return -1;
                }
            }
            if (strcmp(entry->d_name, ".") == 0) continue;
            if (strcmp(entry->d_name, "..") == 0) continue;

            switch (cycle) {
            case 0:
                /* Simple test on inode nr. */
                if (entry->d_ino != current.st_ino) continue;
            /*FALL THROUGH*/

            case 1:
                /* Current is mounted. */
                strcpy(name, "../");
                strcpy(name+3, entry->d_name);
                if (stat(name, &tmp) < 0) continue;
                break;
            }
        } while (tmp.st_ino != current.st_ino
                 || tmp.st_dev != current.st_dev);

        up= p;
        if (addpath(path, &up, entry->d_name) < 0) {
            closedir(d);
            errno = ERANGE;
            recover(p);
            return -1;
        }
        closedir(d);

        if (chdir(dotdot) < 0) {
            recover(p);
            return -1;
        }
        p= up;

        current= above;
    }
    if (recover(p) < 0) return -1;	/* Undo all those chdir("..")'s. */
    if (*p == 0) *--p = '/';	/* Cwd is "/" if nothing added */
    if (p > path) strcpy(path, p);	/* Move string to start of path. */
    return 0;
}