Example #1
0
File: os.cpp Project: nyorain/iro
int os_create_anonymous_file(std::size_t size)
{
   static const char tmplate[] = "/wlc-shared-XXXXXX";

   std::string path = getenv("XDG_RUNTIME_DIR");
   if (path.empty())
      return -1;

	std::string name = path;
	if(path.back() != '/') name.append("/");
	name.append(tmplate);

   int fd = create_tmpfile_cloexec(name.c_str());

   if (fd < 0)
      return -1;

   int ret;
#if HAVE_POSIX_FALLOCATE
   if ((ret = posix_fallocate(fd, 0, size)) != 0) {
      close(fd);
      errno = ret;
      return -1;
   }
#else
   if ((ret = ftruncate(fd, size)) < 0) {
      close(fd);
      return -1;
   }
#endif

   return fd;
}
Example #2
0
/*
 * Create a new, unique, anonymous file of the given size, and
 * return the file descriptor for it. The file descriptor is set
 * CLOEXEC. The file is immediately suitable for mmap()'ing
 * the given size at offset zero.
 *
 * The file should not have a permanent backing store like a disk,
 * but may have if XDG_RUNTIME_DIR is not properly implemented in OS.
 *
 * The file name is deleted from the file system.
 *
 * The file is suitable for buffer sharing between processes by
 * transmitting the file descriptor over Unix sockets using the
 * SCM_RIGHTS methods.
 */
int
os_create_anonymous_file(off_t size)
{
    static const char file[] = "/weston-shared-XXXXXX";
    const char *path;
    char *name;
    int fd;

    path = getenv("XDG_RUNTIME_DIR");
    if (!path) {
        errno = ENOENT;
        return -1;
    }

    name = (char*)malloc(strlen(path) + sizeof(file));
    if (!name)
        return -1;
    strcpy(name, path);
    strcat(name, file);

    fd = create_tmpfile_cloexec(name);

    free(name);

    if (fd < 0)
        return -1;

    if (ftruncate(fd, size) < 0) {
        close(fd);
        return -1;
    }

    return fd;
}