Exemplo n.º 1
0
void *
cserve2_shm_map(Shm_Handle *shm)
{
   int fd;
   const char *name;

   if (shm->refcount++)
     return shm->data;

   name = cserve2_shm_name_get(shm);

   fd = shm_open(name, O_RDWR, S_IWUSR);
   if (fd == -1)
     return MAP_FAILED;

   shm->data = mmap(NULL, shm->image_size, PROT_WRITE, MAP_SHARED,
                    fd, shm->image_offset);

   close(fd);

   return shm->data;
}
Exemplo n.º 2
0
void Cleaner::start() {

    /* Open hash table */
    shmFile = shm_open(shmFilename.c_str(), O_RDWR);
    if (shmFile == -1) {
        std::cout << "[shm_open]:\t" << strerror(errno) << std::endl;
        return;
    }
    hTable = new CHashTable();
    if (hTable->allocate(shmFile) == -1)
        return;

    /* Open semaphore */
    semaphore = sem_open(semFile.c_str(), 0);
    if (semaphore == SEM_FAILED) {
        std::cout << "[sem_open]:\t" << strerror(errno) << std::endl;
        return;
    }

    /* Run cleaner */
    while (true) {

        /* Lock semaphore */
        if (sem_wait(semaphore) == -1) {
            std::cout << "[sem_wait]:\t" << strerror(errno) << std::endl;
            return;
        }

        hTable->checkTTL();

        /* Unlock semaphore */
        if (sem_post(semaphore) == -1) {
            std::cout << "[sem_post]:\t" << strerror(errno) << std::endl;
            return;
        }

        sleep(1);
    }
}
Exemplo n.º 3
0
uintmax_t
test_fstat_shmfd(uintmax_t num, uintmax_t int_arg, const char *path)
{
	struct stat sb;
	uintmax_t i;
	int shmfd;

	shmfd = shm_open(SHM_ANON, O_CREAT | O_RDWR, 0600);
	if (shmfd < 0)
		err(-1, "test_fstat_shmfd: shm_open");
	if (fstat(shmfd, &sb) < 0)
		err(-1, "test_fstat_shmfd: fstat");
	benchmark_start();
	for (i = 0; i < num; i++) {
		if (alarm_fired)
			break;
		(void)fstat(shmfd, &sb);
	}
	benchmark_stop();
	close(shmfd);
	return (i);
}
Exemplo n.º 4
0
//
// shm_open() を使って新しい共有ファイルを作りそれをオープンする
// ただし unlink して共有ファイルは削除し、fd だけを返す。
//
static int
create_shm_file(void)
{
    int fd;
    char tempfile[NAME_MAX];

    snprintf(tempfile, sizeof(tempfile), "/fd-passing-shm-%d", getpid());

    if ((fd = shm_open(tempfile, O_RDWR|O_CREAT, 0644)) == -1) {
        perror("shm_open");
        exit(EXIT_FAILURE);
    }
    
    if (ftruncate(fd, (off_t)TEMPFILE_SIZE)) {
        perror("ftruncate");
        exit(EXIT_FAILURE);
    }

    shm_unlink(tempfile);

    return fd;
}
Exemplo n.º 5
0
void MemArena::GrabLowMemSpace(size_t size)
{
#ifdef _WIN32
#ifndef _XBOX
    hMemoryMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, (DWORD)(size), NULL);
    GetSystemInfo(&sysInfo);
#endif
#elif defined(ANDROID)
    // Use ashmem so we don't have to allocate a file on disk!
    fd = ashmem_create_region("PPSSPP_RAM", size);
    // Note that it appears that ashmem is pinned by default, so no need to pin.
    if (fd < 0)
    {
        ERROR_LOG(MEMMAP, "Failed to grab ashmem space of size: %08x  errno: %d", (int)size, (int)(errno));
        return;
    }
#else
    // Try to find a non-existing filename for our shared memory.
    // In most cases the first one will be available, but it's nicer to search
    // a bit more.
    for (int i = 0; i < 10000; i++)
    {
        std::string file_name = StringFromFormat("/citramem.%d", i);
        fd = shm_open(file_name.c_str(), O_RDWR | O_CREAT | O_EXCL, 0600);
        if (fd != -1)
        {
            shm_unlink(file_name.c_str());
            break;
        }
        else if (errno != EEXIST)
        {
            ERROR_LOG(MEMMAP, "shm_open failed: %s", strerror(errno));
            return;
        }
    }
    if (ftruncate(fd, size) < 0)
        ERROR_LOG(MEMMAP, "Failed to allocate low memory space");
#endif
}
Exemplo n.º 6
0
int main()
{
	int fd = shm_open(SHM_NAME, O_RDWR, 0777);
	if (fd < 0)
	{
		perror("shm_open");
	}
	if (shm_unlink(SHM_NAME) < 0)
	{
		perror("shm_unlink");
	}
	if (sem_unlink(SEM_AFFICHAGE) < 0)
	{
		perror("sem_unlink");
	}
	if (sem_unlink(SEM_MUTEX) < 0)
	{
		perror("sem_unlink");
	}
	Tmorpion* pmorpion = (Tmorpion*) mmap(NULL, sizeof(Tmorpion), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
	close(fd); // on n'a plus besoin du descripteur de fichier
	if (pmorpion == (void*)-1)
	{
		perror("mmap");
	}
	int i;
	char str_sem[17];
	for (i=0; i < NB_MAX_JOUEURS; i++)
	{
		sprintf(str_sem, SEM_JOUEUR"%c", 'a'+i);
		if (sem_unlink(str_sem) < 0)
			perror(str_sem);
	}
	if (munmap((void*)pmorpion, sizeof(Tmorpion)) < 0)
	{
		perror("munmap");
	}
	exit(0);
}
Exemplo n.º 7
0
int shm_mutex_init(key_t key, shm_mutex_t *pshmmutex)
{
  size_t  size = sizeof(pthread_mutex_t);

  if( pshmmutex == NULL )
  {
    LOGERROR("shm_mutex_t structure is NULL.");
    errno = EINVAL;
    return RC_ERROR;
  }

  // create/attach to shared memory mutex
  if( shm_open(key, size, shm_mutex_create, pshmmutex) < 0 )
  {
    LOGSYSERROR("shm_mutex_init(%d=0x%x, ...)", key, key);
    return RC_ERROR;
  }

  LOGDIAG3("Shared memory mutex initialized (key=%d=0x%x, ...)", key, key);

  return OK;
}
Exemplo n.º 8
0
static void* open_shared_memory(char* shm_name, int shm_size, int* shm_fd)
{	
	*shm_fd = shm_open(shm_name, O_RDWR, 0666);
	if (*shm_fd == -1) {
		perror("shm_open");
		return NULL;
	}
	
	void* mem = mmap(0, shm_size, PROT_WRITE | PROT_READ, 
					 MAP_SHARED, *shm_fd, 0);
	if (mem == MAP_FAILED) {
		int rc = close(*shm_fd);
		if (rc == -1) {
			perror("close");
			return NULL;
		}
		perror("mmap");
		return NULL;
	}
	
	return mem;
}
Exemplo n.º 9
0
static struct stats *init_stats_obj(void)
{
	int32_t fd = 0;

    /* Create named shared memory. */
    fd = shm_open(name, O_RDWR, 0666);
    if(fd < 0)
    {
        output(ERROR, "Can't create named shared memory\n");
        return (NULL);
    }

    /* Map named shared object. */
    test_stat = mmap(NULL, sizeof(struct stats), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if(test_stat == MAP_FAILED)
    {
        output(ERROR, "Can't mmap shared object: %s\n", strerror(errno));
        return (NULL);
    }

	return (test_stat);
}
Exemplo n.º 10
0
int main(int argc, char *argv[]){
	int shmfd, error;
	printf("create.c\n\n");
	if(argc != 2){
		printf("usage: ./create [SHM-Name]\n");
		return -1;
	}

	shmfd = shm_open(argv[1], O_CREAT | O_RDWR | O_EXCL, 0666);
	if(shmfd < 1){
		printf("error creating Shared Memory Segment\n");
		return -1;
	}

	error = ftruncate(shmfd, sizeof(shared));
	if(error < 0){
		printf("error setting size of SHM \"%s\"\n",argv[1]);
		return -1;
	}

	shared* myShared = (shared*)mmap(NULL, sizeof(shared), PROT_WRITE, MAP_SHARED, shmfd, 0);	
	if(myShared == MAP_FAILED){
		printf("error mapping Shared Memory Segment\n");
	}

	error = sem_init(&(myShared->sem), 1, 1);
	if(error != 0){
		printf("\nError initializing semaphore. Error: %d\n", error);
	}

	error = munmap(myShared, sizeof(shared));
	if(error < 0){
		printf("error closing Shared Memory Segment\n");
		return -1;
	}

	return 0;
}
Exemplo n.º 11
0
void RDPListener::processDisplaySwitch(std::vector<uint32_t> msg)
{
    // note that under current calling conditions, this will run in the thread of the RDPServerWorker associated with
    // the VM.
    VLOG(2) << "LISTENER " << this << ": Now processing display switch event";
    uint32_t displayWidth = msg.at(2);
    uint32_t displayHeight = msg.at(3);
    pixman_format_code_t displayFormat = (pixman_format_code_t) msg.at(1);
    int shim_fd;
    size_t shm_size = 4096 * 2048 * sizeof(uint32_t);

    // TODO: clear all queues if necessary

    // map in new shmem region if it's the first time
    if (!shm_buffer) {
        std::stringstream ss;
        ss << "/" << vm_id << ".rdpmux";

        VLOG(2) << "LISTENER " << this << ": Creating new shmem buffer from path " << ss.str();
        shim_fd = shm_open(ss.str().data(), O_RDONLY, S_IRUSR | S_IRGRP | S_IROTH);
        VLOG(3) << "LISTENER " << this << ": shim_fd is " << shim_fd;

        void *shm_buffer = mmap(NULL, shm_size, PROT_READ, MAP_SHARED, shim_fd, 0);
        if (shm_buffer == MAP_FAILED) {
            LOG(WARNING) << "mmap() failed: " << strerror(errno);
            // todo: send this information to the backend service so it can trigger a retry
            return;
        }
        VLOG(2) << "LISTENER " << this << ": mmap() completed successfully! Yayyyyyy";
        this->shm_buffer = shm_buffer;
    }

    this->width = displayWidth;
    this->height = displayHeight;
    this->format = displayFormat;

    VLOG(2) << "LISTENER " << this << ": Display switch processed successfully!";
}
Exemplo n.º 12
0
int main(int argc, char *argv[])
{
int pid;
int i=0;
struct shm_cnt *counter;
  pid=fork();
  sleep(1);

//shm_open: first process will create the page, the second will just attach to the same page
//we get the virtual address of the page returned into counter
//which we can now use but will be shared between the two processes
  
shm_open(1,(char **)&counter);
 
//  printf(1,"%s returned successfully from shm_open with counter %x\n", pid? "Child": "Parent", counter); 
  for(i = 0; i < 10000; i++)
    {
     uacquire(&(counter->lock));
     counter->cnt++;
     urelease(&(counter->lock));

//print something because we are curious and to give a chance to switch process
     if(i%1000 == 0)
       printf(1,"Counter in %s is %d at address %x\n",pid? "Parent" : "Child", counter->cnt, counter);
}
  
  if(pid)
     {
       printf(1,"Counter in parent is %d\n",counter->cnt);
    wait();
    } else
    printf(1,"Counter in child is %d\n\n",counter->cnt);

//shm_close: first process will just detach, next one will free up the shm_table entry (but for now not the page)
   shm_close(1);
   exit();
   return 0;
}
Exemplo n.º 13
0
int main()
{

	ring1_int *ringque = NULL;
	int c,fd,flags;
	char *ptr;
	off_t length;
	flags = O_RDWR | O_CREAT;
	length = sizeof(*ringque);
	fd = shm_open("kenny",flags, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
	if(fd < 0){
			printf("error\n");
			exit(0);
	}		
	ftruncate(fd,length);
	ringque = (ring1_int*)mmap(NULL,length,PROT_READ | PROT_WRITE,MAP_SHARED,fd,0);
	printf("%x\n",ringque);
	ring1_int_init(ringque);
	while(1){
		ring1_int_push(ringque,1);
	}
	return 0;
}
Exemplo n.º 14
0
bool SharedObjectsFactory::Initialize()
{
	/*
	 * initialize using POSIX shm
	 */
	int shm_fd = shm_open(SHM_NAME, O_RDWR, 0666);
	if(shm_fd < 0)
	{
		LOG_WARN_WITH_NO("shm_open");
		return false;
	}

	void* addr = mmap(NULL, sizeof(struct SharedMemory), PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
	if(addr == MAP_FAILED)
	{
		LOG_CRITICAL_WITH_NO("mmap");
		return false;
	}

	this->m_addr = (struct SharedMemory*)addr;

	return true;
}
Exemplo n.º 15
0
static void create_shmem(void)
{
	int shm_fd;

	if (asprintf(&shmem_name, "/%s%d", PROGNAME, getpid()) == -1)
		fatal("asprintf (%s)", strerror(errno));

	shm_fd = shm_open(shmem_name, O_CREAT|O_RDWR, S_IRUSR|S_IWUSR);
	if (shm_fd == -1)
		fatal("shm_open");

	if (ftruncate(shm_fd, sizeof(*shm)) == -1)
		fatal("ftruncate");

	shm = mmap(NULL, sizeof(*shm), PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);

	close(shm_fd);

	if (shm == MAP_FAILED)
		fatal("mmap");

	memset(shm, 0, sizeof(*shm));
}
Exemplo n.º 16
0
void* InitSendRecvMem()
{
	int rc;
	send_recv_fd = shm_open(RECV_SEND_MEM, O_CREAT | O_RDWR, 0644);

 	rc = ftruncate(send_recv_fd, 2 * info->proc_nr * getpagesize());
 	DIE(rc == -1, "ftruncate");

 	send_recv_mem = mmap(0, 2 * info->proc_nr * getpagesize(), PROT_READ | PROT_WRITE, MAP_SHARED, send_recv_fd, 0);
 	DIE(send_recv_mem == MAP_FAILED, "mmap");
 	int i;
 	memset(send_recv_mem, 0x0, 2 * info->proc_nr * getpagesize());
 	big_mem_access = malloc(sizeof(sem_t*) * info->proc_nr);

 	for(i = 0; i < info->proc_nr; ++i){
 		char name[40];
 		sprintf(name, "sem_name_%d", i);
	 	big_mem_access[i] = sem_open(name, O_CREAT, 0644, 1); 
		DIE(big_mem_access[i] == SEM_FAILED, "sem_open failed");
	}

	return send_recv_mem;
}
Exemplo n.º 17
0
MmapFile::MmapFile(const char *fileName, const int isShm, 
        const Mode mode, const int pageSize)
    : m_startOffset(0), m_endOffset(0), m_isShm(isShm), 
    m_ptr(NULL), m_fileName(NULL)
{
    int sysPageSize = getpagesize();

    m_pageSize = pageSize > 0 ? pageSize : sysPageSize;
    m_fd = m_isShm ? shm_open(fileName, F_MODE[mode], S_IRUSR | S_IWUSR)
        : open(fileName, F_MODE[mode], S_IRUSR | S_IWUSR);
    if (-1 == m_fd)
    {
        ERRORLOG2("open file %s failed, err %s", 
                fileName, strerror(errno));

        return;
    }

    StrUtil::copy(m_fileName, fileName);
    m_prot = M_MODE[mode];
    m_fileSize = File::getSize(m_fd);
    mapByOffset(0);
}
Exemplo n.º 18
0
void* openPosixSharedMemory()
{
    int shm_fd = shm_open("/MyMemoryMap",O_CREAT | O_RDWR, /*S_IRWXU | S_IRWXG*/0777);
        
    if(shm_fd==-1)
    {        
        perror("shm_open");
        return NULL;
    }
        
    if ( ftruncate(shm_fd, 1000) == -1 ) {
        perror("ftruncate");
        return NULL;
    }    
    
    void *memory = mmap(NULL, 1000, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
    if (memory == NULL) {
        perror("mmap");
        return NULL;
    }
    
    return memory;
}
Exemplo n.º 19
0
uintmax_t
test_dup(uintmax_t num, uintmax_t int_arg, const char *path)
{
	int fd, i, shmfd;

	shmfd = shm_open(SHM_ANON, O_CREAT | O_RDWR, 0600);
	if (shmfd < 0)
		err(-1, "test_dup: shm_open");
	fd = dup(shmfd);
	if (fd >= 0)
		close(fd);
	benchmark_start();
	for (i = 0; i < num; i++) {
		if (alarm_fired)
			break;
		fd = dup(shmfd);
		if (fd >= 0)
			close(fd);
	}
	benchmark_stop();
	close(shmfd);
	return (i);
}
Exemplo n.º 20
0
	bool shared_memory::open(std::string const& _name, size_t _sz)
	{
		shmem_internal *si = shmem_internal::get(mInternal);
		if(!si || si->handle != -1)
			return false;

		int fd = shm_open(_name.c_str(), O_RDWR, 0664);
		if(fd == -1)
			return false;

		void *ptr = mmap(NULL, _sz, PROT_READ | PROT_WRITE,
				MAP_SHARED, fd, 0);
		if(!ptr)
		{
			::close(fd);
			return false;
		}

		si->handle = fd;
		si->pointer = ptr;
		si->size = _sz;
		return true;
	}
Exemplo n.º 21
0
bool PosixSHMTransport::Allocate( bufferstruct *b )
{
	unsigned long rgb32 = 0x32334942;
	if ( b->colorspace == rgb32 || b->colorspace== 0x00)
		b->pitch = 4*b->width;
	else
		return false;
	char fname[50];
	sprintf( fname, "skype_video_frame_nr_%i", bufnum );
	int fd = shm_open(fname,O_RDWR|O_CREAT,0600);
	if ( fd == -1 )
		return false;
	b->bufid = bufnum++;
	b->type = SkypekitVideoTransportBase::PosixSHMBuffer;

	ftruncate( fd, b->pitch*b->height );
	struct bufdata *bdata = new struct bufdata;
	bdata->fd = fd;
	bdata->size = b->pitch*b->height;
	bdata->mem = mmap( 0, bdata->size, PROT_READ|PROT_WRITE,MAP_SHARED, fd, 0 );
	b->clientdata = bdata;
	return true;
}
Exemplo n.º 22
0
int FileLib::createUnnamedSharedMemoryTemp(void) {
	int shmfd = -1;
	char tmpfn[1024];
	pid_t pid = getpid();

	do {
		snprintf(tmpfn, sizeof(tmpfn), "/.%d_tmp_%d", pid, rand());

		errno = 0;
		shmfd = shm_open(tmpfn, O_RDWR | O_CREAT | O_EXCL, 0400);
		if (-1 == shmfd) {
			if (errno != EEXIST) {
				break;
			}
		} else {
			
			shm_unlink(tmpfn);
			break;
		}
	} while (true);

	return shmfd;
}
Exemplo n.º 23
0
int main()
{
    const int SIZE = 1024 * 1024;
    const char *name = "/test.shm";

    int shm_fd;
    void *ptr;

    shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);

    ftruncate(shm_fd,SIZE);

    ptr = mmap(0,SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
    if (ptr == MAP_FAILED)
    {
        printf("Map failed\n");
        return -1;
    }

    memset(ptr, 13, SIZE);

    return 0;
}
Exemplo n.º 24
0
void CMumbleSystem::LevelInitPostEntity()
{
	if ( g_pMumbleMemory )
		return;

#if defined( WIN32 ) && !defined( _X360 )
	g_hMapObject = OpenFileMappingW( FILE_MAP_ALL_ACCESS, FALSE, L"MumbleLink" );
	if ( g_hMapObject == NULL )
		return;

	g_pMumbleMemory = (MumbleSharedMemory_t *) MapViewOfFile( g_hMapObject, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(MumbleSharedMemory_t) );
	if ( g_pMumbleMemory == NULL )
	{
		CloseHandle( g_hMapObject );
		g_hMapObject = NULL;
		return;
	}
#elif defined( POSIX )
	char memname[256];
	V_sprintf_safe( memname, "/MumbleLink.%d", getuid() );

	int shmfd = shm_open( memname, O_RDWR, S_IRUSR | S_IWUSR );

	if ( shmfd < 0 )
	{
		return;
	}

	g_pMumbleMemory = (MumbleSharedMemory_t *)( mmap( NULL, sizeof(struct MumbleSharedMemory_t), PROT_READ | PROT_WRITE, MAP_SHARED, shmfd,0 ) );

	if ( g_pMumbleMemory == (void *)(-1) )
	{
		g_pMumbleMemory = NULL;
		return;
	}
#endif
}
Exemplo n.º 25
0
int main()
{
	int fd;
	unsigned int val;
	struct mydata *addr;
	pthread_mutexattr_t pshared;

	pthread_mutexattr_init(&pshared);
	pthread_mutexattr_setpshared(&pshared, PTHREAD_PROCESS_SHARED);
	pthread_mutexattr_getpshared(&pshared , &val);
	printf(" %d\n", val);
	fd = shm_open(DATA, O_CREAT | O_RDWR, 666);
	if (fd == -1) {
		perror("shm_open");
		exit(1);
	}

	/* 4k is min shared memory */
	if (ftruncate(fd, getpagesize()) == -1) {
		perror("ftruncate");
		exit(1);
	}

	addr =
	    (struct mydata *)mmap(NULL, sizeof(struct mydata),
				  PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
	if (addr == MAP_FAILED) {
		perror("mmap");
		exit(1);
	}
	pthread_mutex_init(&addr->mtxlock, &pshared);
	addr->a = 0;
	addr->b = 0;
	munmap(addr, sizeof(struct mydata));

	return 0;
}
Exemplo n.º 26
0
int main(){

	int fd;
	struct stat sb;

	fd = shm_open("shm", O_RDONLY, 0666);;
	if (fd == -1){
		write(2, "Openning error\n", 20);
		return -1;
	}
	if (fstat(fd, &sb) == -1){
		write(2, "Fstat error\n", 20);
		return -1;
	}
	
	addr = mmap(NULL, sb.st_size, PROT_READ, MAP_SHARED, fd, 0);
	if (addr == MAP_FAILED){
		write(2, "Mapping error\n", 20);
		return -1;
	}

	if (close(fd) == -1){
		write(2, "Closing error\n", 20);
		return -1;
	}
	
	if (signal(40, sigHandler) == SIG_ERR) {
		write(2, "Changing signal handler error\n", 30);
		return -1;
	}
	printf("I am the process with the pid:%d\n", getpid());
	while (1){
		fd = 0;
		fd += 3;
		sleep(3);
	};
}
Exemplo n.º 27
0
int main(int argc, char *argv[])
{
	int r;
	const char *memname = "/mymem";
	const size_t region_size = 1024;
	/* 打开共享内存文件 */
	int fd = shm_open(memname, O_CREAT | O_TRUNC | O_RDWR, 0666);
	if (fd == -1) error_out("shm_open");
	/* 将文件截取至指定的大小 */
	r = ftruncate(fd, region_size);
	if (r != 0) error_out("ftruncate");
	/* 将文件映射为内存 */
	void *ptr = mmap(0, region_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
	if (ptr == MAP_FAILED) error_out("mmap");
	/* 关闭文件 */
	close(fd);
	/* 产生新进程 */
	pid_t pid = fork();
	if (pid == 0) {
		/* 子进程向共享内存写入数据 */
		unsigned long *d = (unsigned long *) ptr;
		*d = 0xdeadbeef;
		exit(0);
	} else {
		/* 父进程等待子进程结束并读共享内存 */
		int status;
		waitpid(pid, &status, 0);
		printf("The data child wrote is %#lx\n", *(unsigned long *)ptr);
	}
	/* 取消内存映射 */
	r = munmap(ptr, region_size);
	if (r != 0) error_out("munmap");
	/* 删除共享内存文件 */
	r = shm_unlink(memname);
	if (r != 0) error_out("shm_unlink");
	return 0;
}
Exemplo n.º 28
0
bool QWSSharedMemory::attach(int id)
{
    if (shmId == id)
        return id != -1;

    detach();

    if (id == -1)
        return false;

    shmId = id;
#ifndef QT_POSIX_IPC
    shmBase = shmat(shmId, 0, 0);
#else
    QByteArray shmName = makeKey(shmId);
    EINTR_LOOP(hand, shm_open(shmName.constData(), O_RDWR, 0660));
    if (hand != -1) {
        // grab the size
        QT_STATBUF st;
        if (QT_FSTAT(hand, &st) != -1) {
            shmSize = st.st_size;
            // grab the memory
            shmBase = mmap(0, shmSize, PROT_READ | PROT_WRITE, MAP_SHARED, hand, 0);
        }
    }
#endif
    if (shmBase == (void*)-1 || !shmBase) {
#ifdef QT_SHM_DEBUG
        perror("QWSSharedMemory::attach():");
        qWarning("Error attaching to shared memory id %d", shmId);
#endif
        detach();
        return false;
    }

    return true;
}
Exemplo n.º 29
0
void sem_test(int num_iterations) {
	char* name = "sem_test";
	int shmfd = shm_open(name, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
	if(shmfd == -1) {
		perror("Could not establish a shared memory object");
		exit(1);
	}

	key_t key = ftok("/usr", 1);
	if(key == -1) {
		perror("Failed to get key");
		unlink_shared_memory(name);
		exit(1);
	}

	int shmid = shmget(key, sizeof(sem_t), 0700 | IPC_CREAT);
	if(shmid == -1) {
		perror("Failed to get memory.");
		unlink_shared_memory(name);
		exit(1);
	}

	sem_t* sems = shmat(shmid, NULL, 0);
	if(sems == (void*)-1) {
		perror("Failed to attach shared memory.");
		unlink_shared_memory(name);
		exit(1);
	}
	
	sem_init(sems, 1, 1);
	perform_sem_test(num_iterations, sems);
	sem_destroy(sems);

	if(unlink_shared_memory(name)) {
		exit(1);
	}
}
Exemplo n.º 30
0
int main(int argc,char **argv)
{
    int shm_id;
    char *ptr;
    sem_t *sem;
    
    if(argc!=2)
    {
        printf("usage:shm_open<pathname>\n");
        exit(1);
    }
    shm_id=shm_open(argv[1],O_RDWR|O_CREAT,0644);
    ftruncate(shm_id,100);
    sem=sem_open(argv[1],O_CREAT,0644,1);
    ptr=mmap(NULL,100,PROT_READ|PROT_WRITE,MAP_SHARED,shm_id,0);
    strcpy(ptr,"\0");
    while(1)
    {
        if((strcmp(ptr,"\0"))==0)
        {
           continue;
        }
        else
        {
            if((strcmp(ptr,"q\n"))==0)
             {
                 break;
             }
             sem_wait(sem);
             printf("server:%s",ptr);
             strcpy(ptr,"\0");
             sem_post(sem);
        }
        sem_unlink(argv[1]);
        shm_unlink(argv[1]);
    }
}