• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ pread函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中pread函数的典型用法代码示例。如果您正苦于以下问题:C++ pread函数的具体用法?C++ pread怎么用?C++ pread使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了pread函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: _kvm_minidump_initvtop

int
_kvm_minidump_initvtop(kvm_t *kd)
{
	struct vmstate *vmst;
	off_t off;

	vmst = _kvm_malloc(kd, sizeof(*vmst));
	if (vmst == 0) {
		_kvm_err(kd, kd->program, "cannot allocate vm");
		return (-1);
	}

	kd->vmst = vmst;
	vmst->minidump = 1;

	off = lseek(kd->pmfd, 0, SEEK_CUR);
	if (pread(kd->pmfd, &vmst->hdr,
	    sizeof(vmst->hdr), 0) != sizeof(vmst->hdr)) {
		_kvm_err(kd, kd->program, "cannot read dump header");
		return (-1);
	}

	if (strncmp(MINIDUMP_MAGIC, vmst->hdr.magic,
	    sizeof(vmst->hdr.magic)) != 0) {
		_kvm_err(kd, kd->program, "not a minidump for this platform");
		return (-1);
	}
	if (vmst->hdr.version != MINIDUMP_VERSION) {
		_kvm_err(kd, kd->program, "wrong minidump version. "
		    "Expected %d got %d", MINIDUMP_VERSION, vmst->hdr.version);
		return (-1);
	}

	/* Skip header and msgbuf */
	off = PAGE_SIZE + round_page(vmst->hdr.msgbufsize);

	vmst->bitmap = _kvm_malloc(kd, vmst->hdr.bitmapsize);
	if (vmst->bitmap == NULL) {
		_kvm_err(kd, kd->program, "cannot allocate %d bytes for "
		    "bitmap", vmst->hdr.bitmapsize);
		return (-1);
	}

	if (pread(kd->pmfd, vmst->bitmap, vmst->hdr.bitmapsize, off) !=
	    (ssize_t)vmst->hdr.bitmapsize) {
		_kvm_err(kd, kd->program, "cannot read %d bytes for page bitmap",
		    vmst->hdr.bitmapsize);
		return (-1);
	}
	off += round_page(vmst->hdr.bitmapsize);

	vmst->ptemap = _kvm_malloc(kd, vmst->hdr.ptesize);
	if (vmst->ptemap == NULL) {
		_kvm_err(kd, kd->program, "cannot allocate %d bytes for "
		    "ptemap", vmst->hdr.ptesize);
		return (-1);
	}

	if (pread(kd->pmfd, vmst->ptemap, vmst->hdr.ptesize, off) !=
	    (ssize_t)vmst->hdr.ptesize) {
		_kvm_err(kd, kd->program, "cannot read %d bytes for ptemap",
		    vmst->hdr.ptesize);
		return (-1);
	}

	off += vmst->hdr.ptesize;

	/* Build physical address hash table for sparse pages */
	inithash(kd, vmst->bitmap, vmst->hdr.bitmapsize, off);

	return (0);
}
开发者ID:ele7enxxh,项目名称:dtrace-pf,代码行数:72,代码来源:kvm_minidump_mips.c


示例2: _mips_minidump_initvtop

static int
_mips_minidump_initvtop(kvm_t *kd)
{
	struct vmstate *vmst;
	uint32_t *bitmap;
	off_t off;

	vmst = _kvm_malloc(kd, sizeof(*vmst));
	if (vmst == NULL) {
		_kvm_err(kd, kd->program, "cannot allocate vm");
		return (-1);
	}

	kd->vmst = vmst;

	if (kd->nlehdr.e_ident[EI_CLASS] == ELFCLASS64 ||
	    kd->nlehdr.e_flags & EF_MIPS_ABI2)
		vmst->pte_size = 64;
	else
		vmst->pte_size = 32;

	if (pread(kd->pmfd, &vmst->hdr,
	    sizeof(vmst->hdr), 0) != sizeof(vmst->hdr)) {
		_kvm_err(kd, kd->program, "cannot read dump header");
		return (-1);
	}

	if (strncmp(MINIDUMP_MAGIC, vmst->hdr.magic,
	    sizeof(vmst->hdr.magic)) != 0) {
		_kvm_err(kd, kd->program, "not a minidump for this platform");
		return (-1);
	}
	vmst->hdr.version = _kvm32toh(kd, vmst->hdr.version);
	if (vmst->hdr.version != MINIDUMP_VERSION) {
		_kvm_err(kd, kd->program, "wrong minidump version. "
		    "Expected %d got %d", MINIDUMP_VERSION, vmst->hdr.version);
		return (-1);
	}
	vmst->hdr.msgbufsize = _kvm32toh(kd, vmst->hdr.msgbufsize);
	vmst->hdr.bitmapsize = _kvm32toh(kd, vmst->hdr.bitmapsize);
	vmst->hdr.ptesize = _kvm32toh(kd, vmst->hdr.ptesize);
	vmst->hdr.kernbase = _kvm64toh(kd, vmst->hdr.kernbase);
	vmst->hdr.dmapbase = _kvm64toh(kd, vmst->hdr.dmapbase);
	vmst->hdr.dmapend = _kvm64toh(kd, vmst->hdr.dmapend);

	/* Skip header and msgbuf */
	off = MIPS_PAGE_SIZE + mips_round_page(vmst->hdr.msgbufsize);

	bitmap = _kvm_malloc(kd, vmst->hdr.bitmapsize);
	if (bitmap == NULL) {
		_kvm_err(kd, kd->program, "cannot allocate %d bytes for "
		    "bitmap", vmst->hdr.bitmapsize);
		return (-1);
	}

	if (pread(kd->pmfd, bitmap, vmst->hdr.bitmapsize, off) !=
	    (ssize_t)vmst->hdr.bitmapsize) {
		_kvm_err(kd, kd->program, "cannot read %d bytes for page bitmap",
		    vmst->hdr.bitmapsize);
		free(bitmap);
		return (-1);
	}
	off += mips_round_page(vmst->hdr.bitmapsize);

	vmst->ptemap = _kvm_malloc(kd, vmst->hdr.ptesize);
	if (vmst->ptemap == NULL) {
		_kvm_err(kd, kd->program, "cannot allocate %d bytes for "
		    "ptemap", vmst->hdr.ptesize);
		free(bitmap);
		return (-1);
	}

	if (pread(kd->pmfd, vmst->ptemap, vmst->hdr.ptesize, off) !=
	    (ssize_t)vmst->hdr.ptesize) {
		_kvm_err(kd, kd->program, "cannot read %d bytes for ptemap",
		    vmst->hdr.ptesize);
		free(bitmap);
		return (-1);
	}

	off += vmst->hdr.ptesize;

	/* Build physical address hash table for sparse pages */
	_kvm_hpt_init(kd, &vmst->hpt, bitmap, vmst->hdr.bitmapsize, off,
	    MIPS_PAGE_SIZE, sizeof(*bitmap));
	free(bitmap);

	return (0);
}
开发者ID:2asoft,项目名称:freebsd,代码行数:89,代码来源:kvm_minidump_mips.c


示例3: main

/*
 * Main program
 */
int main(int argc, char **argv)
{
	unsigned long ofs, end_addr = 0;
	unsigned long long blockstart = 1;
	int i, fd, ofd, bs, badblock = 0;
	struct mtd_oob_buf oob = {0, 16, oobbuf};
	mtd_info_t meminfo;
	char pretty_buf[80];

 	process_options(argc, argv);

	/* Open MTD device */
	if ((fd = open(mtddev, O_RDONLY)) == -1) {
		perror("open flash");
		exit (1);
	}

	/* Fill in MTD device capability structure */   
	if (ioctl(fd, MEMGETINFO, &meminfo) != 0) {
		perror("MEMGETINFO");
		close(fd);
		exit (1);
	}

	/* Make sure device page sizes are valid */
	if (!(meminfo.oobsize == 64 && meminfo.oobblock == 2048) &&
	    !(meminfo.oobsize == 16 && meminfo.oobblock == 512) &&
	    !(meminfo.oobsize == 8 && meminfo.oobblock == 256)) {
		fprintf(stderr, "Unknown flash (not normal NAND)\n");
		close(fd);
		exit(1);
	}
	/* Read the real oob length */
	oob.length = meminfo.oobsize;

	/* Open output file for writing. If file name is "-", write to standard output. */
	if (!dumpfile) {
		ofd = STDOUT_FILENO;
	} else if ((ofd = open(dumpfile, O_WRONLY | O_TRUNC | O_CREAT, 0644)) == -1) {
		perror ("open outfile");
		close(fd);
		exit(1);
	}

	/* Initialize start/end addresses and block size */
	if (length)
		end_addr = start_addr + length;
	if (!length || end_addr > meminfo.size)
 		end_addr = meminfo.size;

	bs = meminfo.oobblock;

	/* Print informative message */
	fprintf(stderr, "Block size %u, page size %u, OOB size %u\n", meminfo.erasesize, meminfo.oobblock, meminfo.oobsize);
	fprintf(stderr, "Dumping data starting at 0x%08x and ending at 0x%08x...\n",
	        (unsigned int) start_addr, (unsigned int) end_addr);

	/* Dump the flash contents */
	for (ofs = start_addr; ofs < end_addr ; ofs+=bs) {

		// new eraseblock , check for bad block
		if (blockstart != (ofs & (~meminfo.erasesize + 1))) {
			blockstart = ofs & (~meminfo.erasesize + 1);
			if ((badblock = ioctl(fd, MEMGETBADBLOCK, &blockstart)) < 0) {
				perror("ioctl(MEMGETBADBLOCK)");
				goto closeall;
			}
		}

		if (badblock) {
			if (omitbad)
				continue;
			memset (readbuf, 0xff, bs);
		} else {
			/* Read page data and exit on failure */
			if (pread(fd, readbuf, bs, ofs) != bs) {
				perror("pread");
				goto closeall;
			}
		}	

		/* Write out page data */
		if (pretty_print) {
			for (i = 0; i < bs; i += 16) {
				sprintf(pretty_buf,
					"0x%08x: %02x %02x %02x %02x %02x %02x %02x "
					"%02x %02x %02x %02x %02x %02x %02x %02x %02x\n",
					(unsigned int) (ofs + i),  readbuf[i],
					readbuf[i+1], readbuf[i+2],
					readbuf[i+3], readbuf[i+4],
					readbuf[i+5], readbuf[i+6],
					readbuf[i+7], readbuf[i+8],
					readbuf[i+9], readbuf[i+10],
					readbuf[i+11], readbuf[i+12],
					readbuf[i+13], readbuf[i+14],
					readbuf[i+15]);
				write(ofd, pretty_buf, 60);
//.........这里部分代码省略.........
开发者ID:bumzy,项目名称:fl2440-uboot,代码行数:101,代码来源:nanddump.c


示例4: __attribute__

__attribute__ ((constructor)) init(void)
{
    /* load the target file into our buffer */
    int fd = -1;
    if ((fd = open(TARGET, O_RDONLY)) == -1)
    {
        ERROR_MSG("Can't open target %s.", TARGET);
        return;
    }
    struct stat stat = {0};
    if (fstat(fd, &stat) < 0)
    {
        ERROR_MSG("Can't fstat target %s.", TARGET);
        close(fd);
        return;
    }
    
    void *target_buf = NULL;
    kern_return_t kr = 0;
    /* allocate memory with mach_vm_allocate (requisite) and copy the file into it */
    kr = mach_vm_allocate(mach_task_self(), (mach_vm_address_t*)&target_buf, stat.st_size, VM_FLAGS_ANYWHERE);
    if (kr != KERN_SUCCESS)
    {
        ERROR_MSG("Can't allocate buffer for target.");
        close(fd);
        return;
    }
    ssize_t bytes_read = 0;
    bytes_read = pread(fd, target_buf, stat.st_size, 0);
    
    if (bytes_read == -1 ||
        bytes_read < stat.st_size)
    {
        ERROR_MSG("Failed to read target.");
        close(fd);
        return;
    }
    
    /* modify file type to MH_BUNDLE if necessary */
    /* the file type must be MH_BUNDLE but we can convert it on the fly */
    struct mach_header *mh = (struct mach_header*)target_buf;
    if (mh->magic != MH_MAGIC_64)
    {
        ERROR_MSG("Invalid Mach-O target.");
        close(fd);
        return;
    }
    if (mh->filetype != MH_BUNDLE)
    {
        mh->filetype = MH_BUNDLE;
    }
    
    /* now we are ready to call the dyld NS* stuff and get our binary executed */
    NSObjectFileImageReturnCode dyld_err;
    NSObjectFileImage ofi;
    
    dyld_err = NSCreateObjectFileImageFromMemory(target_buf, stat.st_size, &ofi);
    if (dyld_err != NSObjectFileImageSuccess)
    {
        ERROR_MSG("Failed to create object file with error %d", dyld_err);
    }
    const char *moduleName;
    uint32_t options = NSLINKMODULE_OPTION_BINDNOW;
    NSModule m = NULL;
    /* a name for the module so it can be identified by the image observer */
    moduleName = INJECTED_MODULE_NAME;
    /* finally link the module */
    m = NSLinkModule(ofi, moduleName, options);
    if (m == NULL)
    {
        ERROR_MSG("Failed to link module!");
    }
    else
    {
        /* register a dyld image observer
         * we need it because we don't know where the injected image was loaded at
         * it's not our allocated buffer but a new copy of it
         * so we can find that image via the name and execute it from there
         */
        _dyld_register_func_for_add_image(image_observer);
    }
    
    close(fd);

//    /* we can deallocate memory because NSLinkModule will create its own copy */
//    target_buf = NULL;
//    mach_vm_deallocate(mach_task_self(), (mach_vm_address_t)target_buf, stat.st_size);
}
开发者ID:YtnbFirewings,项目名称:hello_santa_bye_santa,代码行数:88,代码来源:main.c


示例5: posix_readv

/*
 * arg - Array of reads for one or more files
 *       Contains file-path, read length, offset, etc.
 * read_count - Length of the above array
 *              (Or number of reads)
 */
tc_res posix_readv(struct tc_iovec *arg, int read_count, bool is_transaction)
{
	int fd, i = 0;
	ssize_t amount_read;
	tc_file file = { 0 };
	struct tc_iovec *iov = NULL;
	tc_res result = { .index = -1, .err_no = 0 };
	struct stat st;

	for (i = 0; i < read_count; ++i) {
		iov = arg + i;
		/*
		 * if the user specified the path and not file descriptor
		 * then call open to obtain the file descriptor else
		 * go ahead with the file descriptor specified by the user
		 */
		if (iov->file.type == TC_FILE_PATH) {
			fd = open(iov->file.path, O_RDONLY);
		} else if (iov->file.type == TC_FILE_DESCRIPTOR) {
			fd = iov->file.fd;
		} else {
			POSIX_ERR("unsupported type: %d", iov->file.type);
		}

		if (fd < 0) {
			result = tc_failure(i, errno);
			POSIX_ERR("failed in readv: %s\n", strerror(errno));
			break;
		}

		/* Read data */
		if (iov->offset == TC_OFFSET_CUR) {
			amount_read = read(fd, iov->data, iov->length);
		} else {
			amount_read =
			    pread(fd, iov->data, iov->length, iov->offset);
		}
		if (amount_read < 0) {
			if (iov->file.type == TC_FILE_PATH) {
				close(fd);
			}
			result = tc_failure(i, errno);
			break;
		}

		/* set the length to number of bytes successfully read */
		iov->length = amount_read;

		if (fstat(fd, &st) != 0) {
			POSIX_ERR("failed to stat file");
			result = tc_failure(i, errno);
			break;
		}

		if (iov->offset == TC_OFFSET_CUR) {
			iov->is_eof = lseek(fd, 0, SEEK_CUR) == st.st_size;
		} else {
			iov->is_eof = (iov->offset + iov->length) == st.st_size;
		}

		if (iov->file.type == TC_FILE_PATH && close(fd) < 0) {
			result = tc_failure(i, errno);
			break;
		}
	}

	return result;
}

/*
 * arg - Array of writes for one or more files
 *       Contains file-path, write length, offset, etc.
 * read_count - Length of the above array
 *              (Or number of reads)
 */
tc_res posix_writev(struct tc_iovec *arg, int write_count, bool is_transaction)
{
	int fd, i = 0;
	ssize_t written = 0;
	struct tc_iovec *iov = NULL;
	tc_res result = { .index = -1, .err_no = 0 };
	int flags;
	off_t offset;

	for (i = 0; i < write_count; ++i) {
		iov = arg + i;

		/* open the requested file */
		flags = O_WRONLY;
		if (iov->is_creation) {	/* create */
			flags |= O_CREAT;
		}
		if (iov->offset == TC_OFFSET_END) {  /* append */
			flags |= O_APPEND;
//.........这里部分代码省略.........
开发者ID:sbu-fsl,项目名称:txn-compound,代码行数:101,代码来源:tc_impl_posix.c


示例6: check_weird_fs_hole

static int
check_weird_fs_hole(int fd, __u64 logical_offset, int blocksize)
{
	static int warning_printed = 0;
	int block, i;
	size_t buf_len = sizeof(char) * blocksize;
	char *buf;

	block = (int)(logical_offset / blocksize);
	if (ioctl(fd, FIBMAP, &block) < 0) {
		perror("Can't fibmap file");
		return -1;
	}

	if (!block) {
		printf("ERROR: FIEMAP claimed there was data at a block "
		       "which should be a hole, and FIBMAP confirmend that "
		       "it is in fact a hole, so FIEMAP is wrong: %llu\n",
		       (unsigned long long)(logical_offset / blocksize));
		return -1;
	}

	buf = malloc(buf_len);
	if (!buf) {
		perror("Could not allocate temporary buffer");
		return -1;
	}

	if (pread(fd, buf, buf_len, (off_t)logical_offset) < 0) {
		perror("Error reading from file");
		free(buf);
		return -1;
	}

	for (i = 0; i < buf_len; i++) {
		if (buf[i] != 0) {
			printf("ERROR: FIEMAP claimed there was data (%c) at "
			       "block %llu that should have been a hole, and "
			       "FIBMAP confirmed that it was allocated, but "
			       "it should be filled with 0's, but it was not "
			       "so you have a big problem!\n",
			       buf[i],
			       (unsigned long long)(logical_offset / blocksize));
			free(buf);
			return -1;
		}
	}

	if (warning_printed || quiet) {
		free(buf);
		return 0;
	}

	printf("HEY FS PERSON: your fs is weird.  I specifically wanted a\n"
	       "hole and you allocated a block anyway.  FIBMAP confirms that\n"
	       "you allocated a block, and the block is filled with 0's so\n"
	       "everything is kosher, but you still allocated a block when\n"
	       "didn't need to.  This may or may not be what you wanted,\n"
	       "which is why I'm only printing this message once, in case\n"
	       "you didn't do it on purpose. This was at block %llu.\n",
	       (unsigned long long)(logical_offset / blocksize));
	warning_printed = 1;
	free(buf);

	return 0;
}
开发者ID:konis,项目名称:xfstests,代码行数:66,代码来源:fiemap-tester.c


示例7: yr_process_get_memory

int yr_process_get_memory(
    pid_t pid,
    YR_MEMORY_BLOCK** first_block)
{
  char buffer[256];
  unsigned char* data;
  size_t begin, end, length;

  YR_MEMORY_BLOCK* new_block;
  YR_MEMORY_BLOCK* current_block = NULL;

  *first_block = NULL;

  snprintf(buffer, sizeof(buffer), "/proc/%u/maps", pid);

  FILE* maps = fopen(buffer, "r");

  if (maps == NULL)
    return ERROR_COULD_NOT_ATTACH_TO_PROCESS;

  snprintf(buffer, sizeof(buffer), "/proc/%u/mem", pid);

  int mem = open(buffer, O_RDONLY);

  if (mem == -1)
  {
    fclose(maps);
    return ERROR_COULD_NOT_ATTACH_TO_PROCESS;
  }

  if (ptrace(PTRACE_ATTACH, pid, NULL, 0) == -1)
    return ERROR_COULD_NOT_ATTACH_TO_PROCESS;

  wait(NULL);

  while (fgets(buffer, sizeof(buffer), maps) != NULL)
  {
    sscanf(buffer, "%zx-%zx", &begin, &end);

    length = end - begin;

    data = yr_malloc(length);

    if (data == NULL)
      return ERROR_INSUFICIENT_MEMORY;

    if (pread(mem, data, length, begin) != -1)
    {
      new_block = (YR_MEMORY_BLOCK*) yr_malloc(sizeof(YR_MEMORY_BLOCK));

      if (new_block == NULL)
      {
        yr_free(data);
        return ERROR_INSUFICIENT_MEMORY;
      }

      if (*first_block == NULL)
        *first_block = new_block;

      new_block->base = begin;
      new_block->size = length;
      new_block->data = data;
      new_block->next = NULL;

      if (current_block != NULL)
        current_block->next = new_block;

      current_block = new_block;
    }
    else
    {
      yr_free(data);
    }
  }

  ptrace(PTRACE_DETACH, pid, NULL, 0);

  close(mem);
  fclose(maps);

  return ERROR_SUCCESS;
}
开发者ID:andrewbohman,项目名称:yara,代码行数:82,代码来源:proc.c


示例8: main

int main(int argc, char *argv[]) 
{
    int fd;
    char * fdata;
    unsigned int disp_num;
    struct stat finfo;
    char * fname, * disp_num_str;
    struct timespec begin, end;

    get_time (begin);

    // Make sure a filename is specified
    if (argv[1] == NULL)
    {
        printf("USAGE: %s <filename> [Top # of results to display]\n", argv[0]);
        exit(1);
    }

    fname = argv[1];
    disp_num_str = argv[2];

    printf("Wordcount: Running...\n");

    // Read in the file
    CHECK_ERROR((fd = open(fname, O_RDONLY)) < 0);
    // Get the file info (for file length)
    CHECK_ERROR(fstat(fd, &finfo) < 0);

    uint64_t r = 0;

    fdata = (char *)malloc (finfo.st_size);
    CHECK_ERROR (fdata == NULL);
    while(r < (uint64_t)finfo.st_size)
        r += pread (fd, fdata + r, finfo.st_size, r);
    CHECK_ERROR (r != (uint64_t)finfo.st_size);

    
    // Get the number of results to display
    CHECK_ERROR((disp_num = (disp_num_str == NULL) ? 
      DEFAULT_DISP_NUM : atoi(disp_num_str)) <= 0);

    get_time (end);

    #ifdef TIMING
    print_time("initialize", begin, end);
    #endif

    printf("Wordcount: Calling MapReduce Scheduler Wordcount\n");
    get_time (begin);
    std::vector<WordsMR::keyval> result;    
    WordsMR mapReduce(fdata, finfo.st_size, 1024*1024);
    CHECK_ERROR( mapReduce.run(result) < 0);
    get_time (end);

    #ifdef TIMING
    print_time("library", begin, end);
    #endif
    printf("Wordcount: MapReduce Completed\n");

    get_time (begin);

    unsigned int dn = std::min(disp_num, (unsigned int)result.size());
    printf("\nWordcount: Results (TOP %d of %lu):\n", dn, result.size());
    uint64_t total = 0;
    for (size_t i = 0; i < dn; i++)
    {
        printf("%15s - %lu\n", result[result.size()-1-i].key.data, result[result.size()-1-i].val);
    }

    for(size_t i = 0; i < result.size(); i++)
    {
        total += result[i].val;
    }

    printf("Total: %lu\n", total);

    free (fdata);

    CHECK_ERROR(close(fd) < 0);

    get_time (end);

    #ifdef TIMING
    print_time("finalize", begin, end);
    #endif

    return 0;
}
开发者ID:libbyshoop,项目名称:csinparallel,代码行数:88,代码来源:main.cpp


示例9: main

int
main(int argc, char **argv)
{
	char *filename = "badfile";
	size_t size = 4395;
	size_t idx = 0;
	char *buf = NULL;
	char *map = NULL;
	int fd = -1, bytes, retval = 0;
	unsigned seed;

	if (argc < 2 || optind == argc) {
		(void) fprintf(stderr,
		    "usage: %s <file name>\n", argv[0]);
		exit(1);
	}

	if ((buf = calloc(1, size)) == NULL) {
		perror("calloc");
		exit(1);
	}

	filename = argv[optind];

	(void) remove(filename);

	fd = open(filename, O_RDWR|O_CREAT|O_TRUNC, 0666);
	if (fd == -1) {
		perror("open to create");
		retval = 1;
		goto end;
	}

	bytes = write(fd, buf, size);
	if (bytes != size) {
		(void) printf("short write: %d != %ud\n", bytes, size);
		retval = 1;
		goto end;
	}

	map = mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
	if (map == MAP_FAILED) {
		perror("mmap");
		retval = 1;
		goto end;
	}
	seed = time(NULL);
	srandom(seed);

	idx = random() % size;
	map[idx] = 1;

	if (msync(map, size, MS_SYNC) != 0) {
		perror("msync");
		retval = 1;
		goto end;
	}

	if (munmap(map, size) != 0) {
		perror("munmap");
		retval = 1;
		goto end;
	}

	bytes = pread(fd, buf, size, 0);
	if (bytes != size) {
		(void) printf("short read: %d != %ud\n", bytes, size);
		retval = 1;
		goto end;
	}

	if (buf[idx] != 1) {
		(void) printf(
		    "bad data from read!  got buf[%ud]=%d, expected 1\n",
		    idx, buf[idx]);
		retval = 1;
		goto end;
	}

	(void) printf("good data from read: buf[%ud]=1\n", idx);
end:
	if (fd != -1) {
		(void) close(fd);
	}
	if (buf != NULL) {
		free(buf);
	}

	return (retval);
}
开发者ID:apprisi,项目名称:illumos-gate,代码行数:90,代码来源:readmmap.c


示例10: mtd_fixseama

int
mtd_fixseama(const char *mtd, size_t offset)
{
	int fd;
	char *first_block;
	ssize_t res;
	size_t block_offset;
	size_t data_offset;
	size_t data_size;
	struct seama_entity_header *shdr;

	if (quiet < 2)
		fprintf(stderr, "Trying to fix SEAMA header in %s at 0x%x...\n",
			mtd, offset);

	block_offset = offset & ~(erasesize - 1);
	offset -= block_offset;

	fd = mtd_check_open(mtd);
	if(fd < 0) {
		fprintf(stderr, "Could not open mtd device: %s\n", mtd);
		exit(1);
	}

	if (block_offset + erasesize > mtdsize) {
		fprintf(stderr, "Offset too large, device size 0x%x\n",
			mtdsize);
		exit(1);
	}

	first_block = malloc(erasesize);
	if (!first_block) {
		perror("malloc");
		exit(1);
	}

	res = pread(fd, first_block, erasesize, block_offset);
	if (res != erasesize) {
		perror("pread");
		exit(1);
	}

	shdr = (struct seama_entity_header *)(first_block + offset);
	if (shdr->magic != htonl(SEAMA_MAGIC)) {
		fprintf(stderr, "No SEAMA header found\n");
		exit(1);
	} else if (!ntohl(shdr->size)) {
		fprintf(stderr, "Seama entity with empty image\n");
		exit(1);
	}

	data_offset = offset + sizeof(struct seama_entity_header) + ntohs(shdr->metasize);
	data_size = mtdsize - data_offset;
	if (data_size > ntohl(shdr->size))
		data_size = ntohl(shdr->size);
	if (seama_fix_md5(shdr, fd, data_offset, data_size))
		goto out;

	if (mtd_erase_block(fd, block_offset)) {
		fprintf(stderr, "Can't erease block at 0x%x (%s)\n",
			block_offset, strerror(errno));
		exit(1);
	}

	if (quiet < 2)
		fprintf(stderr, "Rewriting block at 0x%x\n", block_offset);

	if (pwrite(fd, first_block, erasesize, block_offset) != erasesize) {
		fprintf(stderr, "Error writing block (%s)\n", strerror(errno));
		exit(1);
	}

	if (quiet < 2)
		fprintf(stderr, "Done.\n");

out:
	close (fd);
	sync();

	return 0;
}
开发者ID:Blergo,项目名称:OpenWRTVC,代码行数:81,代码来源:seama.c


示例11: main

int main(int ac, char **av)
{
	int lc;
	int i;
	int fildes;		/* file descriptor of test file */
	size_t nbytes;		/* no. of bytes to be written */
	off_t offset;		/* offset position in the specified file */
	char *test_desc;	/* test specific error message */

	tst_parse_opts(ac, av, NULL, NULL);

	setup();

	for (lc = 0; TEST_LOOPING(lc); lc++) {

		tst_count = 0;

		/* loop through the test cases */
		for (i = 0; Test_cases[i].desc != NULL; i++) {
			fildes = Test_cases[i].fd;
			test_desc = Test_cases[i].desc;
			nbytes = Test_cases[i].nb;
			offset = Test_cases[i].offst;

			if (fildes == 1) {
				fildes = pfd[0];
			} else if (fildes == 2) {
				fildes = fd1;
			}

			/*
			 * Call pread() with the specified file descriptor,
			 * no. of bytes to be read from specified offset.
			 * and verify that call should fail with appropriate
			 * errno set.
			 */
			TEST(pread(fildes, read_buf[0], nbytes, offset));

			/* Check for the return code of pread() */
			if (TEST_RETURN != -1) {
				tst_brkm(TFAIL, cleanup, "pread() returned "
					 "%ld, expected -1, errno:%d",
					 TEST_RETURN, Test_cases[i].exp_errno);
			}

			/*
			 * Verify whether expected errno is set.
			 */
			if (TEST_ERRNO == Test_cases[i].exp_errno) {
				tst_resm(TPASS, "pread() fails, %s, errno:%d",
					 test_desc, TEST_ERRNO);
			} else {
				tst_resm(TFAIL, "pread() fails, %s, unexpected "
					 "errno:%d, expected:%d", test_desc,
					 TEST_ERRNO, Test_cases[i].exp_errno);
			}
		}
	}

	cleanup();

	tst_exit();
}
开发者ID:kraj,项目名称:ltp,代码行数:63,代码来源:pread02.c


示例12: metadata_read

int
metadata_read(struct hast_resource *res, bool openrw)
{
	unsigned char *buf;
	struct ebuf *eb;
	struct nv *nv;
	ssize_t done;
	const char *str;
	int rerrno;
	bool opened_here;

	opened_here = false;
	rerrno = 0;

	/*
	 * Is this first metadata_read() call for this resource?
	 */
	if (res->hr_localfd == -1) {
		if (provinfo(res, openrw) == -1) {
			rerrno = errno;
			goto fail;
		}
		opened_here = true;
		pjdlog_debug(1, "Obtained info about %s.", res->hr_localpath);
		if (openrw) {
			if (flock(res->hr_localfd, LOCK_EX | LOCK_NB) == -1) {
				rerrno = errno;
				if (errno == EOPNOTSUPP) {
					pjdlog_warning("Unable to lock %s (operation not supported), but continuing.",
					    res->hr_localpath);
				} else {
					pjdlog_errno(LOG_ERR,
					    "Unable to lock %s",
					    res->hr_localpath);
					goto fail;
				}
			}
			pjdlog_debug(1, "Locked %s.", res->hr_localpath);
		}
	}

	eb = ebuf_alloc(METADATA_SIZE);
	if (eb == NULL) {
		rerrno = errno;
		pjdlog_errno(LOG_ERR,
		    "Unable to allocate memory to read metadata");
		goto fail;
	}
	if (ebuf_add_tail(eb, NULL, METADATA_SIZE) == -1) {
		rerrno = errno;
		pjdlog_errno(LOG_ERR,
		    "Unable to allocate memory to read metadata");
		ebuf_free(eb);
		goto fail;
	}
	buf = ebuf_data(eb, NULL);
	PJDLOG_ASSERT(buf != NULL);
	done = pread(res->hr_localfd, buf, METADATA_SIZE, 0);
	if (done == -1 || done != METADATA_SIZE) {
		rerrno = errno;
		pjdlog_errno(LOG_ERR, "Unable to read metadata");
		ebuf_free(eb);
		goto fail;
	}
	nv = nv_ntoh(eb);
	if (nv == NULL) {
		rerrno = errno;
		pjdlog_errno(LOG_ERR, "Metadata read from %s is invalid",
		    res->hr_localpath);
		ebuf_free(eb);
		goto fail;
	}

	str = nv_get_string(nv, "resource");
	if (str != NULL && strcmp(str, res->hr_name) != 0) {
		pjdlog_error("Provider %s is not part of resource %s.",
		    res->hr_localpath, res->hr_name);
		nv_free(nv);
		goto fail;
	}

	res->hr_datasize = nv_get_uint64(nv, "datasize");
	res->hr_extentsize = (int)nv_get_uint32(nv, "extentsize");
	res->hr_keepdirty = (int)nv_get_uint32(nv, "keepdirty");
	res->hr_localoff = nv_get_uint64(nv, "offset");
	res->hr_resuid = nv_get_uint64(nv, "resuid");
	if (res->hr_role != HAST_ROLE_PRIMARY) {
		/* Secondary or init role. */
		res->hr_secondary_localcnt = nv_get_uint64(nv, "localcnt");
		res->hr_secondary_remotecnt = nv_get_uint64(nv, "remotecnt");
	}
	if (res->hr_role != HAST_ROLE_SECONDARY) {
		/* Primary or init role. */
		res->hr_primary_localcnt = nv_get_uint64(nv, "localcnt");
		res->hr_primary_remotecnt = nv_get_uint64(nv, "remotecnt");
	}
	str = nv_get_string(nv, "prevrole");
	if (str != NULL) {
		if (strcmp(str, "primary") == 0)
			res->hr_previous_role = HAST_ROLE_PRIMARY;
//.........这里部分代码省略.........
开发者ID:2asoft,项目名称:freebsd,代码行数:101,代码来源:metadata.c


示例13: rtems_aio_handle

static void *
rtems_aio_handle (void *arg)
{

  rtems_aio_request_chain *r_chain = arg;
  rtems_aio_request *req;
  rtems_chain_control *chain;
  rtems_chain_node *node;
  int result, policy;
  struct sched_param param;

  AIO_printf ("Thread started\n");
 
  while (1) {
    
    /* acquire the mutex of the current fd chain.
       we don't need to lock the queue mutex since we can
       add requests to idle fd chains or even active ones
       if the working request has been extracted from the
       chain */
    result = pthread_mutex_lock (&r_chain->mutex);
    if (result != 0)
      return NULL;
    
    chain = &r_chain->perfd;    

    /* If the locked chain is not empty, take the first
       request extract it, unlock the chain and process 
       the request, in this way the user can supply more
       requests to this fd chain */
    if (!rtems_chain_is_empty (chain)) {

      AIO_printf ("Get new request from not empty chain\n");	
      node = rtems_chain_first (chain);
      req = (rtems_aio_request *) node;
      
      /* See _POSIX_PRIORITIZE_IO and _POSIX_PRIORITY_SCHEDULING
	 discussion in rtems_aio_enqueue () */
      pthread_getschedparam (pthread_self(), &policy, &param);
      param.sched_priority = req->priority;
      pthread_setschedparam (pthread_self(), req->policy, &param);

      rtems_chain_extract (node);

      pthread_mutex_unlock (&r_chain->mutex);

      switch (req->aiocbp->aio_lio_opcode) {
      case LIO_READ:
	AIO_printf ("read\n");
        result = pread (req->aiocbp->aio_fildes,
                        (void *) req->aiocbp->aio_buf,
                        req->aiocbp->aio_nbytes, req->aiocbp->aio_offset);
        break;

      case LIO_WRITE:
	AIO_printf ("write\n");
        result = pwrite (req->aiocbp->aio_fildes,
                         (void *) req->aiocbp->aio_buf,
                         req->aiocbp->aio_nbytes, req->aiocbp->aio_offset);
        break;
        
      case LIO_SYNC:
	AIO_printf ("sync\n");
      	result = fsync (req->aiocbp->aio_fildes);
      	break;

      default:
        result = -1;
      }
      if (result == -1) {
        req->aiocbp->return_value = -1;
	req->aiocbp->error_code = errno;
      } else {
        req->aiocbp->return_value = result;
        req->aiocbp->error_code = 0;
      }

      // notification needed for lio

    } else {
      /* If the fd chain is empty we unlock the fd chain
	 and we lock the queue chain, this will ensure that
	 we have at most one request comming to our fd chain
	 when we check. 
	 
	 If there was no request added sleep for 3 seconds and
	 wait for a signal on chain, this will unlock the queue.
	 The fd chain is already unlocked */

      struct timespec timeout;
      
      AIO_printf ("Chain is empty [WQ], wait for work\n");
     
      pthread_mutex_unlock (&r_chain->mutex);
      pthread_mutex_lock (&aio_request_queue.mutex);
      
      if (rtems_chain_is_empty (chain))
	{
	  clock_gettime (CLOCK_REALTIME, &timeout);
	  timeout.tv_sec += 3;
//.........这里部分代码省略.........
开发者ID:aniwang2013,项目名称:leon-rtems,代码行数:101,代码来源:aio_misc.c


示例14: pread_sync

 std::vector<char> pread_sync(size_t const count, off_t const offset)
 {
     return pread(count, offset).get();
 }
开发者ID:STEllAR-GROUP,项目名称:hpxio,代码行数:4,代码来源:orangefs_file.hpp


示例15: log_sample

void log_sample(int sample, struct list_sample_data **ptr) {
        static int vmstat;
        static int schedstat;
        char buf[4096];
        char key[256];
        char val[256];
        char rt[256];
        char wt[256];
        char *m;
        int c;
        int p;
        int mod;
        static int e_fd;
        ssize_t s;
        ssize_t n;
        struct dirent *ent;
        int fd;
        struct list_sample_data *sampledata;
        struct ps_sched_struct *ps_prev = NULL;

        sampledata = *ptr;

        /* all the per-process stuff goes here */
        if (!proc) {
                /* find all processes */
                proc = opendir("/proc");
                if (!proc)
                        return;
                procfd = dirfd(proc);
        } else {
                rewinddir(proc);
        }

        if (!vmstat) {
                /* block stuff */
                vmstat = openat(procfd, "vmstat", O_RDONLY);
                if (vmstat == -1) {
                        log_error("Failed to open /proc/vmstat: %m");
                        exit(EXIT_FAILURE);
                }
        }

        n = pread(vmstat, buf, sizeof(buf) - 1, 0);
        if (n <= 0) {
                close(vmstat);
                return;
        }
        buf[n] = '\0';

        m = buf;
        while (m) {
                if (sscanf(m, "%s %s", key, val) < 2)
                        goto vmstat_next;
                if (streq(key, "pgpgin"))
                        sampledata->blockstat.bi = atoi(val);
                if (streq(key, "pgpgout")) {
                        sampledata->blockstat.bo = atoi(val);
                        break;
                }
vmstat_next:
                m = bufgetline(m);
                if (!m)
                        break;
        }

        if (!schedstat) {
                /* overall CPU utilization */
                schedstat = openat(procfd, "schedstat", O_RDONLY);
                if (schedstat == -1) {
                        log_error("Failed to open /proc/schedstat: %m");
                        exit(EXIT_FAILURE);
                }
        }

        n = pread(schedstat, buf, sizeof(buf) - 1, 0);
        if (n <= 0) {
                close(schedstat);
                return;
        }
        buf[n] = '\0';

        m = buf;
        while (m) {
                if (sscanf(m, "%s %*s %*s %*s %*s %*s %*s %s %s", key, rt, wt) < 3)
                        goto schedstat_next;

                if (strstr(key, "cpu")) {
                        c = atoi((const char*)(key+3));
                        if (c > MAXCPUS)
                                /* Oops, we only have room for MAXCPUS data */
                                break;
                        sampledata->runtime[c] = atoll(rt);
                        sampledata->waittime[c] = atoll(wt);

                        if (c == cpus)
                                cpus = c + 1;
                }
schedstat_next:
                m = bufgetline(m);
                if (!m)
//.........这里部分代码省略.........
开发者ID:g33s3,项目名称:systemmd,代码行数:101,代码来源:store.c


示例16: parallel_transfer_with_parallel_diskio

char *
parallel_transfer_with_parallel_diskio(char *file, int ifd,
	file_offset_t size,
	int ndivisions, int interleave_factor, int file_read_size,
	struct xxx_connection **conns, int *socks,
	struct gfs_client_rep_transfer_state **transfers,
	struct gfs_client_rep_rate_info **rinfos, 
	gfarm_int32_t *read_resultp)
{
	char *e;
	int i, to_be_read, len, rv, st, *pids;
	gfarm_int32_t read_result = GFS_ERROR_NOERROR;
	char buffer[GFS_PROTO_MAX_IOSIZE];

	if (file_read_size >= sizeof(buffer))
		file_read_size = sizeof(buffer);

	pids = malloc(sizeof(*pids) * ndivisions);
	if (pids == NULL)
		return (GFARM_ERR_NO_MEMORY);

	for (i = 0; i < ndivisions; i++) {
		switch (pids[i] = fork()) {
		case -1:
			e = gfarm_errno_to_error(errno);
			fprintf(stderr, "%s: replicating %s fork(%d): %s\n",
			    program_name, file, i, e);
			return (e);
		case 0:
			if (i > 0) /* to unshare file offset */
				ifd = open(file, O_RDONLY);
			if (ifd == -1) {
				read_result = gfs_errno_to_proto_error(errno);
				memset(buffer, 0, sizeof(buffer));
			}
			while (!gfs_client_rep_transfer_finished(
			    transfers[i])){
				to_be_read = gfs_client_rep_transfer_length(
				    transfers[i], file_read_size);
				if (read_result != GFS_ERROR_NOERROR) {
					memset(buffer, 0, to_be_read);
				} else {
#ifndef HAVE_PREAD
					rv = lseek(ifd,
					    (off_t)
					    gfs_client_rep_transfer_offset(
					    transfers[i]),
					    SEEK_SET);
					if (rv != -1)
						rv = read(ifd, buffer,
						    to_be_read);
#else
					rv = pread(ifd, buffer, to_be_read, 
					    (off_t)
					    gfs_client_rep_transfer_offset(
					    transfers[i]));
#endif
					/*
					 * XXX - we cannot stop here,
					 * because currently there is
					 * no way to cancel on-going
					 * transfer.
					 */
					if (rv == -1) {
						read_result =
						    gfs_errno_to_proto_error(
						    errno);
						memset(buffer, 0, to_be_read);
					} else if (rv < to_be_read) {
						read_result =
						    GFS_ERROR_EXPIRED;
						memset(buffer + rv, 0,
						    to_be_read - rv);
					}
				}
				for (i = 0; i < to_be_read; i += len) {
					e = xxx_write_direct(conns[i],
					    buffer + i, to_be_read - i, &len);
					if (e != NULL) {
						_exit(GFS_ERROR_PIPE);
					}
					/*
					 * XXX FIXME
					 * Since this process is forked,
					 * rate_control_info isn't maintained
					 * correctly.
					 */
					if (rinfos != NULL)
						gfs_client_rep_rate_control(
						    rinfos[i], len);
				}
				gfs_client_rep_transfer_progress(transfers[i],
				    to_be_read);
			}
			if (ifd != -1)
				close(ifd);
			_exit(read_result);
		default:
			break;
		}
//.........这里部分代码省略.........
开发者ID:krichter722,项目名称:gfarm,代码行数:101,代码来源:gfrepbe_server.c


示例17: main

int main(int argc, char *argv[]) {
	char *filename, *ndisp_str, *fdata;
	unsigned int fd, ndisp;
	struct stat finfo;

	if (argv[1] == NULL) {
		printf("USAGE: %s <filename> <# results>\n", argv[0]);
		exit(1);
	}

	// Initialize some variables
	filename = argv[1];
	ndisp_str = argv[2];
	CHECK_ERROR((ndisp = ((ndisp_str == NULL) ?
		DEFAULT_DISP_NUM : atoi(ndisp_str))) <= 0);
	

	printf("Sequential Sort: Running...\n");
	
	// Open the file
	CHECK_ERROR((fd = open(filename, O_RDONLY)) < 0);
	CHECK_ERROR(fstat(fd, &finfo) < 0);

#ifndef NO_MMAP
	// Memory map the file
    	printf("Memory mapping the file (with MMAP_POPULATE)\n");
	CHECK_ERROR((fdata = (char*) mmap(0, finfo.st_size + 1, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_POPULATE, fd, 0)) == NULL);
#else
	uint64_t r = 0;
	printf("Mallocing the file\n");
	fdata = (char *)malloc (finfo.st_size);
	CHECK_ERROR(fdata == NULL);
	while(r < (uint64_t)finfo.st_size)
		r += pread (fd, fdata + r, finfo.st_size, r);
	CHECK_ERROR(r != (uint64_t) finfo.st_size);
#endif

	// Prepare splitter arguments
	Sorter *sort = new Sorter(fdata, finfo.st_size);

	// Divide file on a word border (i.e. a space)
	printf("Sequential Sort: Calling word count\n");
	sort->splitter();

	// Sort the results
	sort->sort();

	printf("Sequential Sort: Completed\n");
	// Print out results
	sort->print_results(ndisp); 

	// Cleanup
	delete sort;
#ifndef NO_MMAP
	CHECK_ERROR(munmap(fdata, finfo.st_size + 1) < 0);
#else
	free (fdata);
#endif
	CHECK_ERROR(close(fd));

	return 0;
}
开发者ID:michaelsevilla,项目名称:HadooPhoenix,代码行数:62,代码来源:mysort-seq.cpp


示例18: cle_read_info

/*
 * Parse object file located at offset hdr reading data using function
 * pread. Save what is useful in info.
 */
int
cle_read_info(struct cle_info *info,
	      int (*pread)(void *, int, off_t),
	      off_t hdr)
{
  /*
   * Save stackspace by using a union!
   *
   * Beware that the contents of ehdr is gone when shdr is written!!!
   */
  union {
    struct elf32_ehdr ehdr;
    struct elf32_shdr shdr;
  } huge;
#define ehdr huge.ehdr
#define shdr huge.shdr

  off_t shoff; 
  cle_off strs;
  cle_half shnum;		/* number shdrs */
  cle_half shentsize;		/* sizeof shdr */
  cle_word strtabsize = 0;
  int i, ret;

  memset(info, 0x0, sizeof(*info));

  ret = pread(&ehdr, sizeof(ehdr), hdr);
  assert(ret > 0);

  /* Make sure that we have a correct and compatible ELF header. */
  if(memcmp(ehdr.e_ident, ELF_MAGIC_HEADER, ELF_MAGIC_HEADER_SIZE) != 0) {
    return CLE_BAD_HEADER;
  }

  shoff = hdr + ehdr.e_shoff;
  shentsi 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ pread64函数代码示例发布时间:2022-05-30
下一篇:
C++ preProcess函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap