void write_log_file(char *filename, char *data) {
    FILE *file = NULL;
    int fd = 0;
    char time_str[6];
    struct flock* fl = file_lock(F_WRLCK, SEEK_SET);

    fd = open(filename, O_RDWR);
    if (fd == -1) {
        printf("File descriptor error");
        exit(1);
    }
    
    if (fcntl(fd, F_SETLK, fl) == -1) {
        if (errno == EACCES || errno == EAGAIN) {
            printf("File locked by another process.\n");
        } else {
            printf("Unexpected error. Quitting.\n");
        }
    } else {
        file = fopen(filename, "a");
        if (file != NULL) {
            get_current_time(time_str);
            fprintf(file, "%s ", time_str);
            fprintf(file, "EMP: %s\n", data);
        } else {
            printf("Error writing to log file!\n");
            exit(1);
        }
        
        fcntl(fd, F_SETLKW, file_lock(F_UNLCK, SEEK_SET));
        fclose(file);
    }
}
示例#2
0
int main()
{
	int i;	
	char buf[1024] = {0};
	int len;
	
	int fd = open("1.txt", O_WRONLY|O_APPEND);
	if(fd == -1)
	{	
		printf("Open File Fail!!!!\n");
		return -1;
	}
	else
		printf("Open File Suc\n");
			
	for(i=0; i<10; ++i) 
	{		
		fcntl(fd, F_SETLKW, file_lock(F_WRLCK, SEEK_SET));
		sprintf(buf, "hello world %d\n", i);
		len = strlen(buf);
		printf("XXXXXXXXXXXXXXXXXXXXXX Buf: %s, Len: %d\n", buf, strlen(buf));
		
		write(fd, buf, len);
		fcntl(fd, F_SETLKW, file_lock(F_UNLCK, SEEK_SET));
		sleep(1);
	}	
	
	if(close(fd) == -1)
	{	
		printf("Close File Fail!!!!\n");
		return -1;
	}	
	
	return 0;
}
示例#3
0
文件: log.c 项目: SamStudio8/SGCNIS
/**
 * Write to the log file.
 * This method will first try to obtain a lock on the log file; if it is free,
 * it will create a lock, write to the file and release it.
 * If it is not free, the user is warned and asked whether they wish to try
 * writing to the file again.
 *
 * @param l Pointer to the application log.
 * @param line The line to append to the log file.
 */
void writeLog(log* l, char line[256]){
    char path[256] = "";
    strcat(strcat(path, l->pwd), "log.txt");
    
    int logFileDescriptor = open(path, O_RDWR);
    if (logFileDescriptor == -1) {
        printf("WARNING! The log file could not be found.\nAll actions will go"
                " un-logged until this is rectified.\nYou may need to change "
                "the PWD with the 'W' command on the main menu.\n");
    }
    else{
        //Check the lock.
        struct flock* lock = file_lock(F_WRLCK, SEEK_SET);
        if (fcntl(logFileDescriptor, F_SETLK, lock) == -1) {
            if (errno == EACCES || errno == EAGAIN) {
                //File locked by another application.
                char option = 0;
                while(option != 'y' && option != 'Y'
                        && option != 'n' && option != 'N'){
                    option = promptChar("The log file is in use by another "
                            "application, do you wish to try writing to it "
                            "again? [Y/N]", "%1c");
                }

                switch(option){
                    case 'Y':
                    case 'y':
                        writeLog(l, line);
                        break;
                    case 'N':
                    case 'n':
                        break;
                }
            } else {
                printf("\nWARNING! An unexpected error occurred writing to the"
                        " log file, your action was not appended.\n");
            }
        } else {
            //Generate timestamp.
            time_t t;
            struct tm * timestamp;
            char str_timestamp[80];

            time (&t);
            timestamp = localtime (&t);
            strftime(str_timestamp, 80, "[%d/%m/%y %X] ", timestamp);

            //Log file locked, write to file.
            FILE* logFile = fopen(path, "a+");
            fprintf(logFile, strcat(str_timestamp, line));

            //Release the file lock and close.
            fcntl(logFileDescriptor, F_SETLKW, file_lock(F_UNLCK, SEEK_SET));
            fclose(logFile);
        }
    }
}
示例#4
0
void *startfilepwent(char *pfile, char *s_readbuf, int bufsize,
				int *file_lock_depth, BOOL update)
{
  FILE *fp = NULL;

  if (!*pfile)
 {
    DEBUG(0, ("startfilepwent: No file set\n"));
    return (NULL);
  }
  DEBUG(10, ("startfilepwent: opening file %s\n", pfile));

  fp = sys_fopen(pfile, update ? "r+b" : "rb");

  if (fp == NULL) {
    DEBUG(0, ("startfilepwent: unable to open file %s\n", pfile));
    return NULL;
  }

  /* Set a buffer to do more efficient reads */
  setvbuf(fp, s_readbuf, _IOFBF, bufsize);

  if (!file_lock(fileno(fp), (update ? F_WRLCK : F_RDLCK), 5, file_lock_depth))
  {
    DEBUG(0, ("startfilepwent: unable to lock file %s\n", pfile));
    fclose(fp);
    return NULL;
  }

  /* Make sure it is only rw by the owner */
  chmod(pfile, 0600);

  /* We have a lock on the file. */
  return (void *)fp;
}
示例#5
0
        /**
         *  @return 成功:文件ID 失败:-1
         */
        int get_lock()
        {
            int li_lck_st = -1;
            file_ = open("/tmp/dbinit", O_RDWR|O_CREAT, 0777);
            if( file_ <= 0 )
            {
                //perror("file open error");
                return -1;
            }
            if(-1 == (li_lck_st = file_lock()))
            {
                close(file_);
                file_ = 0;
                //perror("lock file fail");
                return -1;
            }
            if(-1 == lseek(file_, 0, SEEK_SET))
            {
                perror("lseek faild");
                file_unlock();
                return -1;
            }
            if(-1 == read(file_, &status_, sizeof(int)))
            {
                //perror("read faild");
            }

            printf("read status %d\n", status_);
            return li_lck_st;
        }
示例#6
0
apr_status_t apr_file_trunc(apr_file_t *fp, apr_off_t offset)
{
    if (fp->buffered) {
        int rc = 0;
        file_lock(fp);
        if (fp->direction == 1 && fp->bufpos != 0) {
            apr_off_t len = fp->filePtr + fp->bufpos;
            if (offset < len) {
                /* New file end fall below our write buffer limit.
                 * Figure out if and what needs to be flushed.
                 */
                apr_off_t off = len - offset;
                if (off >= 0 && off <= fp->bufpos)
                    fp->bufpos = fp->bufpos - (size_t)off;
                else
                    fp->bufpos = 0;
            }
            rc = apr_file_flush_locked(fp);
            /* Reset buffer positions for write mode */
            fp->bufpos = fp->direction = fp->dataRead = 0;
        }
        file_unlock(fp);
        if (rc) {
            return rc;
        }
    }
    if (ftruncate(fp->filedes, offset) == -1) {
        return errno;
    }
    return apr_file_seek(fp, APR_SET, &offset);
}
示例#7
0
int HDRecordFileReader::ReadPosRecord()
{
    std::string index_file = _filepath + ".ind";
    ACE_File_Lock file_lock(_file_handler);
    int ret = 0;
    _file_handler = ACE_OS::dup(file_lock.get_handle());
    if(file_lock.tryacquire())
    {
        ACE_DEBUG((LM_ERROR,"锁定记录文件失败[%s]",_filepath.c_str()));
        return -1;
    }
    try
    {
        ACE_DEBUG((LM_DEBUG,"锁定记录文件成功,开始分析..."));
        ret = DoReadRecordFile();
    }
    catch(...)
    {
        ACE_DEBUG((LM_ERROR,"处理记录文件异常......."));
    }

    if(ret)
    {
        ACE_DEBUG((LM_ERROR,"保存记录失败"));
    }
    else
    {
        ACE_OS::unlink(index_file.c_str());
    }
    if(file_lock.release())
    {
        ACE_DEBUG((LM_ERROR,"释放记录文件失败[%s]",_filepath.c_str()));
    }
    return ret;
}
示例#8
0
文件: buffer.c 项目: Ga-vin/apache
APR_DECLARE(apr_status_t) apr_file_buffer_set(apr_file_t *file, 
                                              char * buffer,
                                              apr_size_t bufsize)
{
    apr_status_t rv;

    file_lock(file);

    if(file->buffered) {
        /* Flush the existing buffer */
        rv = apr_file_flush_locked(file);
        if (rv != APR_SUCCESS) {
            file_unlock(file);
            return rv;
        }
    }
        
    file->buffer = buffer;
    file->bufsize = bufsize;
    file->buffered = 1;
    file->bufpos = 0;
    file->direction = 0;
    file->dataRead = 0;
 
    if (file->bufsize == 0) {
            /* Setting the buffer size to zero is equivalent to turning 
             * buffering off. 
             */
            file->buffered = 0;
    }

    file_unlock(file);

    return APR_SUCCESS;
}
/* Finds the next element of the given directory and stores the element's name
   in the given buffer. Returns true if an element was found, false if not.
   NOTE : "." and ".." are not considered true elements, and will never be
   returned by this function. */
bool
dir_readdir (struct file *dir, char *buf)
{
  ASSERT (file_is_dir (dir));
  bool locked = file_lock (dir);

  /* If the cursor is before the third entry, then it's pointing at "." or "..",
     since these are *always* the first two directory entries. Seek to beyond
     them, since we don't want to return them. */
  off_t min_cursor = 2 * sizeof (struct dir_entry);
  if (file_tell (dir) < min_cursor)
    file_seek (dir, min_cursor);

  bool success = false;
  while (true)
    {
      struct dir_entry e;
      if (file_read (dir, &e, sizeof e) != sizeof e)
        goto done;
      if (e.in_use)
        {
          strlcpy (buf, e.name, NAME_MAX + 1);
          return true;
          goto done;
        }
    }
    
done:
  if (locked) file_unlock (dir);
  return success;
}
示例#10
0
void
modstatdb_lock(void)
{
    if (!modstatdb_can_lock())
        ohshit(_("you do not have permission to lock the dpkg status database"));

    file_lock(&dblockfd, FILE_LOCK_NOWAIT, lockfile, _("dpkg status database"));
}
示例#11
0
static int flock_wrapper( string fname, int flag, int fd ) {
    int res;

    seteuid( socket_info[ fd ][ USER_NAME ] );
    res = file_lock( fname, flag );
    seteuid( getuid() );

    return res;
}
示例#12
0
APR_DECLARE(apr_status_t) apr_file_writev(apr_file_t *thefile, const struct iovec *vec,
                                          apr_size_t nvec, apr_size_t *nbytes)
{
#ifdef HAVE_WRITEV
    apr_status_t rv;
    int bytes;

    if (thefile->buffered) {
        file_lock(thefile);

        rv = apr_file_flush_locked(thefile);
        if (rv != APR_SUCCESS) {
            file_unlock(thefile);
            return rv;
        }
        if (thefile->direction == 0) {
            /* Position file pointer for writing at the offset we are
             * logically reading from
             */
            apr_int64_t offset = thefile->filePtr - thefile->dataRead +
                                 thefile->bufpos;
            if (offset != thefile->filePtr)
                lseek(thefile->filedes, offset, SEEK_SET);
            thefile->bufpos = thefile->dataRead = 0;
        }

        file_unlock(thefile);
    }

    if ((bytes = writev(thefile->filedes, vec, nvec)) < 0) {
        *nbytes = 0;
        rv = errno;
    }
    else {
        *nbytes = bytes;
        rv = APR_SUCCESS;
    }
    return rv;
#else
    /**
     * The problem with trying to output the entire iovec is that we cannot
     * maintain the behavoir that a real writev would have.  If we iterate
     * over the iovec one at a time, we loose the atomic properties of 
     * writev().  The other option is to combine the entire iovec into one
     * buffer that we could then send in one call to write().  This is not 
     * reasonable since we do not know how much data an iovec could contain.
     *
     * The only reasonable option, that maintains the semantics of a real 
     * writev(), is to only write the first iovec.  Callers of file_writev()
     * must deal with partial writes as they normally would. If you want to 
     * ensure an entire iovec is written, use apr_file_writev_full().
     */

    *nbytes = vec[0].iov_len;
    return apr_file_write(thefile, vec[0].iov_base, nbytes);
#endif
}
示例#13
0
/* file [mode] [offset [length]] -- file/nil error */
static int ex_lock(lua_State *L)
{
  FILE *f = check_file(L, 1, NULL);
  int argi = 2;
  const char *mode = opt_mode(L, &argi);
  long offset = (long)luaL_optnumber(L, argi, 0);
  long length = (long)luaL_optnumber(L, argi + 1, 0);
  return file_lock(L, f, mode, offset, length);
}
示例#14
0
bool
release_lock(
    int		fd)
{
    int i =::fcntl(fd, F_SETLK, file_lock(F_UNLCK, SEEK_SET));
//   if (i == -1)
//     fmwkout << "Release lock failed " << errno << dendl;

    return i != -1;
}
示例#15
0
文件: a2.c 项目: duck12212/OS-Lab
int main(){
        int i;
        int fd=open("b.txt",O_RDWR|O_APPEND);
        printf("Choosing lock:\n");
        printf("1. exclusive lock(write lock).  2. share lock(read lock). 3. not use lock\n");
        scanf("%d",&i);
 if(i==1) {
        if(fcntl(fd,F_SETLK,file_lock(F_WRLCK,SEEK_SET))==0){
          printf("Locking file with 'WRLCK' success.\n");
        }
        else{
          printf("Locking file with 'WRLCK' fail, another process lock it.\n");
        }
        }
        else if(i==2){
          if(fcntl(fd,F_SETLK,file_lock(F_RDLCK,SEEK_SET))==0){
          printf("Locking file with 'RDLCK' success.\n");
          char ca[10000];
          if(read(fd, ca, 10000)<0)printf("Can't read file.\n");
          else
          {
            printf("Read file:\n");
            puts(ca);
          }

        }
        else{
          printf("Locking file with 'RDLCK' fail, another process lock it.\n");
        }
        }
        else if(i==3){
          char ca[10000];
          if(read(fd, ca, 10000)<0)printf("Can't read file.\n");
          else
          {
            printf("Read file:\n");
            puts(ca);
          }
        }
         fcntl(fd, F_SETLK, file_lock(F_UNLCK, SEEK_SET));
        close(fd);

}
示例#16
0
bool
write_lock(
    int		fd)
{
    int i =::fcntl(fd, F_SETLK, file_lock(F_WRLCK, SEEK_SET));
//   if (i == -1)
//     fmwkout << "Write lock failed " << errno << dendl;

    return i != -1;
}
示例#17
0
/*FUNCTION*/
int hook_lock(pExecuteObject pEo,
              FILE *fp,
              int iLockType,
              long lStart,
              long lLength
  ){
  return file_lock(fp,iLockType,lStart,lLength);
/*noverbatim
CUT*/
  }
示例#18
0
int unlock(int file_descriptor) {
	if(file_descriptor == -1) {
		printf("Cannot unlock file: File Descriptor Error\n");
		return 0;
	} else {
		fcntl(file_descriptor, F_SETLKW, file_lock(F_UNLCK, SEEK_SET));
		close(file_descriptor);
		return 1;
	}
}
示例#19
0
APR_DECLARE(apr_status_t) apr_file_gets(char *str, int len, apr_file_t *thefile)
{
    apr_status_t rv = APR_SUCCESS; /* get rid of gcc warning */
    apr_size_t nbytes;
    const char *str_start = str;
    char *final = str + len - 1;

    if (len <= 1) {  
        /* sort of like fgets(), which returns NULL and stores no bytes 
         */
        return APR_SUCCESS;
    }

    /* If we have an underlying buffer, we can be *much* more efficient
     * and skip over the apr_file_read calls.
     */
    if (thefile->buffered) {

        file_lock(thefile);

        if (thefile->direction == 1) {
            rv = apr_file_flush_locked(thefile);
            if (rv) {
                file_unlock(thefile);
                return rv;
            }

            thefile->direction = 0;
            thefile->bufpos = 0;
            thefile->dataRead = 0;
        }

        while (str < final) { /* leave room for trailing '\0' */
            /* Force ungetc leftover to call apr_file_read. */
            if (thefile->bufpos < thefile->dataRead &&
                thefile->ungetchar == -1) {
                *str = thefile->buffer[thefile->bufpos++];
            }
            else {
                nbytes = 1;
                rv = file_read_buffered(thefile, str, &nbytes);
                if (rv != APR_SUCCESS) {
                    break;
                }
            }
            if (*str == '\n') {
                ++str;
                break;
            }
            ++str;
        }

        file_unlock(thefile);
    }
示例#20
0
int main(int argc,char *argv[])
{
    int fd = open(argv[1], O_WRONLY|O_APPEND);
	int i;
	time_t now;
    for(i=0; i<1000; ++i) {
        fcntl(fd, F_SETLKW, file_lock(F_WRLCK, SEEK_SET));
		time(&now);
		printf("%s\t%s F_SETLKW  lock file %s for 3sec\n",ctime(&now),argv[0],argv[1]);
        char buf[1024] = {0};
        sprintf(buf, "china %d\n", i);
        int len = strlen(buf);
        if(write(fd, buf, len))
			printf("%s\t%s write file sccess\n",ctime(&now),argv[0],argv[1]);
        sleep(3);
		fcntl(fd, F_SETLKW, file_lock(F_UNLCK, SEEK_SET));
		sleep(1);
    }
    close(fd);
}
示例#21
0
QuillErrCode FILESQL::file_updateEvent(const char *eventType, 
									   AttrList *info, 
									   AttrList *condition) {
	int retval = 0;
	struct stat file_status;

    if (is_dummy) return QUILL_SUCCESS;
	if(!is_open)
	{
		dprintf(D_ALWAYS,"Error in logging event to Quill SQL Log : File not open\n");
		return QUILL_FAILURE;
	}

	if(file_lock() == QUILL_FAILURE) {
		return QUILL_FAILURE;
	}

	fstat(outfiledes, &file_status);

		// only write to the log if it's not exceeding the log size limit
	if (file_status.st_size < FILESIZELIMT) {
		retval = write(outfiledes,"UPDATE ", strlen("UPDATE "));
		retval = write(outfiledes,eventType, strlen(eventType));
		retval = write(outfiledes,"\n", strlen("\n"));

		MyString temp, temp1;
		const char *tempv;

		retval = sPrintAd(temp, *info);
		tempv = temp.Value();
		retval = write(outfiledes,tempv, strlen(tempv));

		retval = write(outfiledes,"***",3); /* Now the delimitor*/
		retval = write(outfiledes,"\n",1); /* Now the newline*/

		retval = sPrintAd(temp1, *condition);
		tempv = temp1.Value();
		retval = write(outfiledes,tempv, strlen(tempv));
		
		retval = write(outfiledes,"***",3); /* Now the delimitor*/
		retval = write(outfiledes,"\n",1); /* Now the newline*/	
	}

	if(file_unlock() == QUILL_FAILURE) {
		return QUILL_FAILURE;
	}

	if (retval < 0) {
		return QUILL_FAILURE;	
	} else {
		return QUILL_SUCCESS;	
	}
}
示例#22
0
int mdev_wdm_main(int argc, char **argv)
{
	FILE *fp;
	int isLock;
	char node_fname[64];
	const char *device_name, *action;

	if(argc != 3){
		printf("Usage: %s [device_name] [action]\n", argv[0]);
		return 0;
	}

	device_name = argv[1];
	action = argv[2];

	usb_dbg("(%s): action=%s.\n", device_name, action);
	
	if(!isWDMNode(device_name))
		return 0;
	
	sprintf(node_fname, "%s/%s", MODEM_NODE_DIR, device_name);
	
	// Check Lock.
	if((isLock = file_lock((char *)device_name)) == -1)
		return 0;
	
	unlink(QMI_CLIENT_ID);
	
	// If remove the device?
	if(!check_hotplug_action(action)){
		unlink(node_fname);
		goto out_unlock;
	}
	
	// Write node file.
	mkdir_if_none(MODEM_NODE_DIR);
	fp = fopen(node_fname, "w+");
	if (fp) {
		fprintf(fp, "pref=%d\n", 1);
		fprintf(fp, "devnum=%d\n", 0); // todo
		fclose(fp);
	}
	
	usb_dbg("(%s): Success!\n", device_name);
	
out_unlock:
	file_unlock(isLock);
	
	return 1;
}
示例#23
0
APR_DECLARE(apr_status_t) apr_file_flush(apr_file_t *thefile)
{
    apr_status_t rv = APR_SUCCESS;

    if (thefile->buffered) {
        file_lock(thefile);
        rv = apr_file_flush_locked(thefile);
        file_unlock(thefile);
    }
    /* There isn't anything to do if we aren't buffering the output
     * so just return success.
     */
    return rv; 
}
示例#24
0
/* also based on Neal's code */
void append_to_file(char* filename, char* line) {
	struct flock* fl;
	FILE* fp;
	int fd = open(filename, O_RDWR);

	if (fd == -1) {
		/* I'm going to assume that I can't get a descriptor because the file doesn't */
		/* exist yet, so let's create it with a call to fopen */
		fp = fopen(filename, "a+");
		fclose(fp);
		/* and then try again */
		fd = open(filename, O_RDWR);
		if (fd == -1) {
			/* bad times! */
			printf("Error getting file descriptor\n");
			exit(1);
		}
	}

	fl = file_lock(F_WRLCK, SEEK_SET);

	while (fcntl(fd, F_SETLK, fl) == -1) {
		if (errno != EACCES && errno != EAGAIN) {
			/* bad times! */
			printf("can't get lock\n");
			exit(1);
		}
	}

	/* so now we have a lock */

	fp = fopen(filename, "a+");
	fprintf(fp, "%s\n", line);

	fcntl(fd, F_SETLKW, file_lock(F_UNLCK, SEEK_SET));
	fclose(fp);
}
示例#25
0
int mdev_sg_main(int argc, char **argv)
{
	int isLock;
	const char *device_name, *action;

	if(argc < 3){
		printf("Usage: %s [device_name] [action]\n", argv[0]);
		return 0;
	}

	device_name = argv[1];
	action = argv[2];

	usb_dbg("(%s): action=%s.\n", device_name, action);

	if(get_device_type_by_device(device_name) != DEVICE_TYPE_SG)
		return 0;

	// If remove the device?
	if(!check_hotplug_action(action)){
		usb_dbg("(%s): Remove sg device.\n", device_name);
		return 0;
	}

	// Check Lock.
	if((isLock = file_lock((char *)device_name)) == -1){
		usb_dbg("(%s): Can't set the file lock!\n", device_name);
		return 0;
	}

	if (nvram_get_int("modem_zcd") != 0) {
		if (module_smart_load("sr_mod"))
			sleep(1);
	}
	else {
		char vid[8] = {0}, pid[8] = {0};
		char usb_port_id[64] = {0};
		if (get_usb_port_by_device(device_name, usb_port_id, sizeof(usb_port_id))) {
			if (get_usb_vid(usb_port_id, vid, sizeof(vid)) && get_usb_pid(usb_port_id, pid, sizeof(pid)))
				perform_usb_modeswitch(vid, pid);
		}
	}

	usb_dbg("(%s): Success!\n", device_name);
	file_unlock(isLock);

	return 1;
}
示例#26
0
static void write_config(const config_t * config,const char * table, const char * file)
{
	char * filename;
	char * fullname;

	filename = strconcat(table,"/",file,NULL);

	fullname = strconcat(base_directory,"/",filename,NULL);

	file_lock(filename);
	config_write_file((config_t*)config,fullname);
	file_unlock(filename);

	free(filename);
	free(fullname);
}
示例#27
0
文件: posix.c 项目: hno/fribid
/**
 * Opens a file and locks it for reading or writing. If Platform_OpenCreate
 * is specified as the mode then the file is created, and the function fails
 * if it already exists to prevent overwrites and race conditions.
 *
 * @param mode  Either Platform_OpenRead or Platform_OpenCreate
 */
FILE *platform_openLocked(const char *filename, PlatformOpenMode mode) {
    static const char *const stdio_modes[] = { "rb", "wb" };
    static const int open_flags[] = { O_RDONLY, O_WRONLY|O_CREAT|O_EXCL };
    static const int lock_flags[] = { F_RDLCK, F_WRLCK };

    int fd = open(filename, open_flags[mode], 0600);
    if (fd == -1) return NULL;
    
    struct flock lk = file_lock(lock_flags[mode]);
    if (fcntl(fd, F_SETLKW, &lk) != 0) {
        close(fd);
        return NULL;
    }
    
    return fdopen(fd, stdio_modes[mode]);
}
示例#28
0
APR_DECLARE(apr_status_t) apr_file_seek(apr_file_t *thefile, apr_seek_where_t where, apr_off_t *offset)
{
    apr_off_t rv;

    thefile->eof_hit = 0;

    if (thefile->buffered) {
        int rc = EINVAL;
        apr_finfo_t finfo;

        file_lock(thefile);

        switch (where) {
        case APR_SET:
            rc = setptr(thefile, *offset);
            break;

        case APR_CUR:
            rc = setptr(thefile, thefile->filePtr - thefile->dataRead + thefile->bufpos + *offset);
            break;

        case APR_END:
            rc = apr_file_info_get_locked(&finfo, APR_FINFO_SIZE, thefile);
            if (rc == APR_SUCCESS)
                rc = setptr(thefile, finfo.size + *offset);
            break;
        }

        *offset = thefile->filePtr - thefile->dataRead + thefile->bufpos;

        file_unlock(thefile);

        return rc;
    }
    else {
        rv = lseek(thefile->filedes, *offset, where);
        if (rv == -1) {
            *offset = -1;
            return errno;
        }
        else {
            *offset = rv;
            return APR_SUCCESS;
        }
    }
}
/* Adds a file named NAME to DIR, which must not already contain a
   file by that name.  The file's inode is in sector
   INODE_SECTOR.
   Returns true if successful, false on failure.
   Fails if NAME is invalid (i.e. too long) or a disk or memory
   error occurs. */
bool
dir_add (struct file *dir, const char *name, block_sector_t inode_sector)
{
  ASSERT (file_is_dir (dir));
  struct dir_entry e;
  size_t ofs;
  bool success = false;

  ASSERT (dir != NULL);
  ASSERT (name != NULL);

  /* Check NAME for validity. */
  if (*name == '\0' || strlen (name) > NAME_MAX)
    return false;

  bool locked = file_lock (dir);
  /* Check that NAME is not in use. */
  if (dir_lookup (dir, name) >= 0)
    goto done;

  /* Set OFS to offset of free slot.
     If there are no free slots, then it will be set to the
     current end-of-file.
     
     inode_read_at() will only return a short read at end of file.
     Otherwise, we'd need to verify that we didn't get a short
     read due to something intermittent such as low memory. */
  size_t dir_size = inode_length (dir->inode);
  for (ofs = 0; ofs < dir_size; ofs += sizeof e) 
    {
      inode_read_at (dir->inode, &e, sizeof e, ofs);
      if (!e.in_use)
        break;
    }

  /* Write slot. */
  e.in_use = true;
  strlcpy (e.name, name, sizeof e.name);
  e.inode_sector = inode_sector;
  success = inode_write_at (dir->inode, &e, sizeof e, ofs) == sizeof e;

 done:
  if (locked) file_unlock (dir);
  return success;
}
示例#30
0
int sfx_play(context_t* p_Ctx, const std::string & p_FileName, int p_Channel,
		int p_Loops)
{
	auto l_It = g_SoundList.find(p_FileName);

	if (l_It != g_SoundList.end())
	{
		return Mix_PlayChannel(p_Channel, l_It->second, p_Loops);
	}

	const std::string l_TableFilename = std::string(SFX_TABLE)
			+ std::string("/") + p_FileName;
	const std::string l_FullName = std::string(base_directory) + "/"
			+ l_TableFilename;

	file_lock(l_TableFilename.c_str());

	SDL_RWops * l_pFileDesc = SDL_RWFromFile(l_FullName.c_str(), "r");
	if (l_pFileDesc == nullptr)
	{
		std::string l_Err = std::string("sfx_play: cannot open ")
				+ l_FullName.c_str();
		werr(LOGDESIGNER, l_Err.c_str());
		file_update(p_Ctx, l_TableFilename.c_str());
		file_unlock(l_TableFilename.c_str());
		return -1;
	}

	Mix_Chunk * l_pChunk = Mix_LoadWAV_RW(l_pFileDesc, 1);
	if (l_pChunk == nullptr)
	{
		std::string l_Err = std::string("sfx_play: cannot read ")
				+ l_FullName.c_str();
		werr(LOGDESIGNER, l_Err.c_str());
		file_update(p_Ctx, l_TableFilename.c_str());
		file_unlock(l_TableFilename.c_str());
		return -1;
	}

	g_SoundList[p_FileName] = l_pChunk;

	file_unlock(l_TableFilename.c_str());

	return Mix_PlayChannel(p_Channel, l_pChunk, p_Loops);
}