Пример #1
1
void* icvVideoRender(void* data)
{
    int cameraid = (int)data;
    CvVideoCamera *const camera = &(cameras[cameraid]);
    Display* display;
    int screen_num;
    GC gc;
    char* display_name = NULL;
    Window window = camera->window;
    XWindowAttributes windowattr;
    Visual* visual;
    int windowdepth;
    XImage* image;
    XShmSegmentInfo xshmseg;
    int width  = (camera->renderwidth>0)?camera->renderwidth:camera->videopp.width;
    int height = camera->renderheight?camera->renderheight:camera->videopp.height;
    int picturedepth = camera->videopp.picture.depth;
    int pixelsize;
    XGCValues values;
    IplImage* iplimage;
    time_t start, now;
    int frames = 0;
    float rate = 0;
    Status XShm;
    uchar* imgdata = NULL;
    uchar* tmpbuff = NULL;

    pthread_mutex_lock(&(camera->capturestatemutex));
    if(camera->capturestate != CAPTURING)
    {
        pthread_mutex_unlock(&(camera->capturestatemutex));
        pthread_exit( NULL );
    }
    camera->renderstate=1;
    pthread_cond_signal(&(camera->capturestatecond));
    pthread_mutex_unlock(&(camera->capturestatemutex));
    XInitThreads();

    if ( (display=XOpenDisplay(display_name)) == NULL )

    {
        fprintf( stderr, "cvVideo: cannot connect to X server %s\n",
            XDisplayName(display_name));
        pthread_exit( NULL );
    }

    screen_num = DefaultScreen(display);

    if (XGetWindowAttributes(display, window,
        &windowattr) == 0)
    {
        fprintf(stderr, "icvVideoRender: failed to get window attributes.\n" );
        pthread_exit(NULL);
    }

    if(windowattr.map_state == IsUnmapped)
    {
        fprintf(stderr, "icvVideoRender: window is not mapped \n" );
        pthread_exit(NULL);
    }

    windowdepth = windowattr.depth;
    visual      = windowattr.visual;

    pixelsize = icvVideoWindowPixelsize(windowdepth);

    XShm = XShmQueryExtension(display);
    if(XShm)
    {
        image = XShmCreateImage(display, visual, windowdepth, ZPixmap, NULL,
            &xshmseg, width, height );

        assert(image);

        xshmseg.shmid = shmget (IPC_PRIVATE,
            width*height*pixelsize, IPC_CREAT|0777);

        assert(xshmseg.shmid != -1);
        xshmseg.shmaddr = image->data=(char*)shmat (xshmseg.shmid, 0, 0) ;

        xshmseg.readOnly = False;

        XShmAttach (display, &xshmseg);
    }
    else
    {
        imgdata = (uchar*)malloc(width*height*icvVideoWindowPixelsize(windowdepth)) ;
        image = XCreateImage(display, visual, windowdepth, ZPixmap, 0,
            (char*)imgdata, width,
            height, 8,
            icvVideoWindowPixelsize(windowdepth)
            *width);

        assert(image);
        XInitImage(image);
    }

    gc = XCreateGC(display,window,0, &values );
#ifdef RENDER_FRAMERATE
    start = time(NULL);
#endif

    pthread_mutex_lock(&(camera->capturestatemutex));
    while((camera->capturestate == CAPTURING) && (camera->rendered))
    {
        pthread_mutex_unlock(&(camera->capturestatemutex));
        pthread_mutex_lock(&(camera->updatedmutex));
        while(camera->updated == 0)
            pthread_cond_wait(&(camera->updatedcond), &(camera->updatedmutex));
        camera->updated = 0;
        pthread_mutex_unlock(&(camera->updatedmutex));
        if(cvcamGetProperty(cameraid, "raw_image",&iplimage ))
        {
            assert(image->data);
            if(camera->callback != NULL)
                camera->callback(iplimage);
            if((width==camera->videopp.width)&&
               (height==camera->videopp.height))
            {
                icvvConvert(width, height, width*picturedepth/8, picturedepth,
                            iplimage->imageData, width*pixelsize, pixelsize*8, image->data
                    );
                cvReleaseImage(&iplimage);
            }
            else
            {
                tmpbuff = (uchar*)malloc(camera->videopp.width*camera->videopp.height*
                                         pixelsize) ;
                
                icvvConvert(camera->videopp.width, camera->videopp.height,
                            camera->videopp.width*picturedepth/8, picturedepth,
                            iplimage->imageData, camera->videopp.width*pixelsize,
                            pixelsize*8, (char*)tmpbuff);
                cvReleaseImage(&iplimage);
                
                icvvResizeImage(camera->videopp.width,
                                camera->videopp.height,
                                (camera->videopp.width)*pixelsize, (char*)tmpbuff,
                                width, height,width*pixelsize, image->data, pixelsize*8);
                
                free(tmpbuff);
                
            }
            
            //fprintf(stdout, "cvVideoRendering:image converted!!!!\n");
            
            if(XShm)
            {
                XShmPutImage(display, window, gc,
                             image,0,0,0,0, width,
                             height, False);
            }
            else
            {
                XPutImage(display, window, gc,
                          image,0,0,0,0, width,
                          height);
            }
            
            XSync(display, False);
#ifdef RENDER_FRAMERATE            
            now = time(NULL);
            frames++;
            if (now-start)
                rate = frames/(float)(now-start);
            if((frames%30) == 0)
                fprintf(stdout, "camera %d fps = %f\n", cameraid, rate);
#endif
        }//if(cvcamGetProperty(CAMERA, "raw_image",&image ))

        // stop here if we're paused
        pthread_mutex_lock(&(camera->pausemutex));
        pthread_mutex_unlock(&(camera->pausemutex));
        pthread_mutex_lock(&(camera->capturestatemutex));
    }//while (camera->state == CAPTURING && camera->rendered)
    pthread_mutex_unlock(&(camera->capturestatemutex));

    pthread_mutex_lock(&(camera->capturestatemutex));
#if 0
    if(camera->state != CAPTURING) {
        // we ended because the camera is not capturing anymore
        while (camera->capturestate != FINISHED )
        {
            pthread_cond_wait(&(camera->capturestatecond),&(camera->capturestatemutex));
        }
    }
#endif
    camera->renderstate=0;
    pthread_cond_signal(&(camera->capturestatecond));
    pthread_mutex_unlock(&(camera->capturestatemutex));

    XShmDetach (display, &xshmseg);
    XDestroyImage (image);
    XFreeGC(display,gc);
    shmdt (xshmseg.shmaddr);
    shmctl (xshmseg.shmid, IPC_RMID, 0);
    if(imgdata)
        free(imgdata);  
    pthread_exit(NULL);
}
Пример #2
0
/*
 * Operating system primitives to support System V shared memory.
 *
 * System V shared memory segments are manipulated using shmget(), shmat(),
 * shmdt(), and shmctl().  There's no portable way to resize such
 * segments.  As the default allocation limits for System V shared memory
 * are usually quite low, the POSIX facilities may be preferable; but
 * those are not supported everywhere.
 */
static bool
dsm_impl_sysv(dsm_op op, dsm_handle handle, Size request_size,
			  void **impl_private, void **mapped_address, Size *mapped_size,
			  int elevel)
{
	key_t		key;
	int			ident;
	char	   *address;
	char		name[64];
	int		   *ident_cache;

	/* Resize is not supported for System V shared memory. */
	if (op == DSM_OP_RESIZE)
	{
		elog(elevel, "System V shared memory segments cannot be resized");
		return false;
	}

	/* Since resize isn't supported, reattach is a no-op. */
	if (op == DSM_OP_ATTACH && *mapped_address != NULL)
		return true;

	/*
	 * POSIX shared memory and mmap-based shared memory identify segments with
	 * names.  To avoid needless error message variation, we use the handle as
	 * the name.
	 */
	snprintf(name, 64, "%u", handle);

	/*
	 * The System V shared memory namespace is very restricted; names are of
	 * type key_t, which is expected to be some sort of integer data type, but
	 * not necessarily the same one as dsm_handle.  Since we use dsm_handle to
	 * identify shared memory segments across processes, this might seem like
	 * a problem, but it's really not.  If dsm_handle is bigger than key_t,
	 * the cast below might truncate away some bits from the handle the
	 * user-provided, but it'll truncate exactly the same bits away in exactly
	 * the same fashion every time we use that handle, which is all that
	 * really matters.  Conversely, if dsm_handle is smaller than key_t, we
	 * won't use the full range of available key space, but that's no big deal
	 * either.
	 *
	 * We do make sure that the key isn't negative, because that might not be
	 * portable.
	 */
	key = (key_t) handle;
	if (key < 1)				/* avoid compiler warning if type is unsigned */
		key = -key;

	/*
	 * There's one special key, IPC_PRIVATE, which can't be used.  If we end
	 * up with that value by chance during a create operation, just pretend it
	 * already exists, so that caller will retry.  If we run into it anywhere
	 * else, the caller has passed a handle that doesn't correspond to
	 * anything we ever created, which should not happen.
	 */
	if (key == IPC_PRIVATE)
	{
		if (op != DSM_OP_CREATE)
			elog(DEBUG4, "System V shared memory key may not be IPC_PRIVATE");
		errno = EEXIST;
		return false;
	}

	/*
	 * Before we can do anything with a shared memory segment, we have to map
	 * the shared memory key to a shared memory identifier using shmget(). To
	 * avoid repeated lookups, we store the key using impl_private.
	 */
	if (*impl_private != NULL)
	{
		ident_cache = *impl_private;
		ident = *ident_cache;
	}
	else
	{
		int			flags = IPCProtection;
		size_t		segsize;

		/*
		 * Allocate the memory BEFORE acquiring the resource, so that we don't
		 * leak the resource if memory allocation fails.
		 */
		ident_cache = MemoryContextAlloc(TopMemoryContext, sizeof(int));

		/*
		 * When using shmget to find an existing segment, we must pass the
		 * size as 0.  Passing a non-zero size which is greater than the
		 * actual size will result in EINVAL.
		 */
		segsize = 0;

		if (op == DSM_OP_CREATE)
		{
			flags |= IPC_CREAT | IPC_EXCL;
			segsize = request_size;
		}

		if ((ident = shmget(key, segsize, flags)) == -1)
		{
			if (errno != EEXIST)
			{
				int			save_errno = errno;

				pfree(ident_cache);
				errno = save_errno;
				ereport(elevel,
						(errcode_for_dynamic_shared_memory(),
						 errmsg("could not get shared memory segment: %m")));
			}
			return false;
		}

		*ident_cache = ident;
		*impl_private = ident_cache;
	}

	/* Handle teardown cases. */
	if (op == DSM_OP_DETACH || op == DSM_OP_DESTROY)
	{
		pfree(ident_cache);
		*impl_private = NULL;
		if (*mapped_address != NULL && shmdt(*mapped_address) != 0)
		{
			ereport(elevel,
					(errcode_for_dynamic_shared_memory(),
				   errmsg("could not unmap shared memory segment \"%s\": %m",
						  name)));
			return false;
		}
		*mapped_address = NULL;
		*mapped_size = 0;
		if (op == DSM_OP_DESTROY && shmctl(ident, IPC_RMID, NULL) < 0)
		{
			ereport(elevel,
					(errcode_for_dynamic_shared_memory(),
				  errmsg("could not remove shared memory segment \"%s\": %m",
						 name)));
			return false;
		}
		return true;
	}

	/* If we're attaching it, we must use IPC_STAT to determine the size. */
	if (op == DSM_OP_ATTACH)
	{
		struct shmid_ds shm;

		if (shmctl(ident, IPC_STAT, &shm) != 0)
		{
			ereport(elevel,
					(errcode_for_dynamic_shared_memory(),
					 errmsg("could not stat shared memory segment \"%s\": %m",
							name)));
			return false;
		}
		request_size = shm.shm_segsz;
	}

	/* Map it. */
	address = shmat(ident, NULL, PG_SHMAT_FLAGS);
	if (address == (void *) -1)
	{
		int			save_errno;

		/* Back out what's already been done. */
		save_errno = errno;
		if (op == DSM_OP_CREATE)
			shmctl(ident, IPC_RMID, NULL);
		errno = save_errno;

		ereport(elevel,
				(errcode_for_dynamic_shared_memory(),
				 errmsg("could not map shared memory segment \"%s\": %m",
						name)));
		return false;
	}
	*mapped_address = address;
	*mapped_size = request_size;

	return true;
}
Пример #3
0
static NOINLINE void do_shm(void)
{
	int maxid, shmid, id;
	struct shmid_ds shmseg;
	struct shm_info shm_info;
	struct shminfo shminfo;
	struct ipc_perm *ipcp = &shmseg.shm_perm;
	struct passwd *pw;

	maxid = shmctl(0, SHM_INFO, (struct shmid_ds *) (void *) &shm_info);
	if (maxid < 0) {
		printf("kernel not configured for %s\n", "shared memory");
		return;
	}

	switch (format) {
	case LIMITS:
		printf("------ Shared Memory %s --------\n", "Limits");
		if ((shmctl(0, IPC_INFO, (struct shmid_ds *) (void *) &shminfo)) < 0)
			return;
		/* glibc 2.1.3 and all earlier libc's have ints as fields
		 * of struct shminfo; glibc 2.1.91 has unsigned long; ach */
		printf("max number of segments = %lu\n"
				"max seg size (kbytes) = %lu\n"
				"max total shared memory (pages) = %lu\n"
				"min seg size (bytes) = %lu\n",
				(unsigned long) shminfo.shmmni,
				(unsigned long) (shminfo.shmmax >> 10),
				(unsigned long) shminfo.shmall,
				(unsigned long) shminfo.shmmin);
		return;

	case STATUS:
		printf("------ Shared Memory %s --------\n", "Status");
		printf("segments allocated %d\n"
				"pages allocated %lu\n"
				"pages resident  %lu\n"
				"pages swapped   %lu\n"
				"Swap performance: %lu attempts\t%lu successes\n",
				shm_info.used_ids,
				shm_info.shm_tot,
				shm_info.shm_rss,
				shm_info.shm_swp,
				shm_info.swap_attempts, shm_info.swap_successes);
		return;

	case CREATOR:
		printf("------ Shared Memory %s --------\n", "Segment Creators/Owners");
		printf("%-10s %-10s %-10s %-10s %-10s %-10s\n",
				"shmid", "perms", "cuid", "cgid", "uid", "gid");
		break;

	case TIME:
		printf("------ Shared Memory %s --------\n", "Attach/Detach/Change Times");
		printf("%-10s %-10s %-20s %-20s %-20s\n",
				"shmid", "owner", "attached", "detached", "changed");
		break;

	case PID:
		printf("------ Shared Memory %s --------\n", "Creator/Last-op");
		printf("%-10s %-10s %-10s %-10s\n",
				"shmid", "owner", "cpid", "lpid");
		break;

	default:
		printf("------ Shared Memory %s --------\n", "Segments");
		printf("%-10s %-10s %-10s %-10s %-10s %-10s %-12s\n",
				"key", "shmid", "owner", "perms", "bytes", "nattch",
				"status");
		break;
	}

	for (id = 0; id <= maxid; id++) {
		shmid = shmctl(id, SHM_STAT, &shmseg);
		if (shmid < 0)
			continue;
		if (format == CREATOR) {
			print_perms(shmid, ipcp);
			continue;
		}
		pw = getpwuid(ipcp->uid);
		switch (format) {
		case TIME:
			if (pw)
				printf("%-10d %-10.10s", shmid, pw->pw_name);
			else
				printf("%-10d %-10d", shmid, ipcp->uid);
			/* ctime uses static buffer: use separate calls */
			printf(" %-20.16s", shmseg.shm_atime
					? ctime(&shmseg.shm_atime) + 4 : "Not set");
			printf(" %-20.16s", shmseg.shm_dtime
					? ctime(&shmseg.shm_dtime) + 4 : "Not set");
			printf(" %-20.16s\n", shmseg.shm_ctime
					? ctime(&shmseg.shm_ctime) + 4 : "Not set");
			break;
		case PID:
			if (pw)
				printf("%-10d %-10.10s", shmid, pw->pw_name);
			else
				printf("%-10d %-10d", shmid, ipcp->uid);
			printf(" %-10d %-10d\n", shmseg.shm_cpid, shmseg.shm_lpid);
			break;

		default:
			printf("0x%08x ", ipcp->KEY);
			if (pw)
				printf("%-10d %-10.10s", shmid, pw->pw_name);
			else
				printf("%-10d %-10d", shmid, ipcp->uid);
			printf(" %-10o %-10lu %-10ld %-6s %-6s\n", ipcp->mode & 0777,
					/*
					 * earlier: int, Austin has size_t
					 */
					(unsigned long) shmseg.shm_segsz,
					/*
					 * glibc-2.1.3 and earlier has unsigned short;
					 * Austin has shmatt_t
					 */
					(long) shmseg.shm_nattch,
					ipcp->mode & SHM_DEST ? "dest" : " ",
					ipcp->mode & SHM_LOCKED ? "locked" : " ");
			break;
		}
	}
}
Пример #4
0
int
main (int argc, char **argv)
{
  int i;
  struct timeval s, t;
  int pfdr[2];
  int pfdw[2];
  int writefd, readfd;
  int status;
  int sid;
  int *shmaddr;
  int val;
  int r;

  printf("TESTING PIPE\n");

  if (pipe(pfdw) < 0) {
    printf("pipe problems, call the plumber\n");
    return (0);
  } else {
    printf("pipe ok, fd0: %d fd1: %d\n", pfdw[0], pfdw[1]);
  }
  readfd = pfdw[0];
  writefd = pfdw[1];

  printf("good test\n");
  status = write(writefd, "test", 5);
  printf("write status %d, errno: %d\n", status, errno);
  status = read(readfd, buffer, 5);
  printf("read status %d, errno: %d\n", status, errno);
  printf("buffer: %s\n", buffer);

  printf("permissions test\n");
  status = write(readfd, "test", 5);
  printf("write status %d, errno: %d\n",status, errno);
  status = read(writefd, buffer, 5);
  printf("read status %d, errno: %d\n", status, errno);
  printf("buffer: %s\n", buffer);


  /* Create a second pipe */
  if (pipe(pfdr) < 0) {
    printf("pipe problems, call the plumber\n");
    return (0);
  } else {
    printf("pipe ok, fd0: %d fd1: %d\n",pfdr[0],pfdr[1]);
  }

  if ((sid = shmget(IPC_PRIVATE, 4096, IPC_CREAT)) < 0) {
      perror("shmget");
  }

  printf("sid %d\n", sid);


  printf("VCOPY\n");

  for (i=0; i < sizeof(buffer); i++)
    buffer[i] = buffer[i];
  for (i=0; i < sizeof(aarray); i++)
    aarray[i] = aarray[i];
  gettimeofday(&s, NULL);
  for (i = 0; i < N; i++) {
      if ((r = sys_vcopyout(buffer, __envid, (u_long) aarray, 1)) != 0) {
	  printf("vcopy failed %d\n", r);
      }
  }
  gettimeofday(&t, NULL);
  printf("%d vcopy: in %lu usec\n", N, 
	 (t.tv_sec - s.tv_sec) * 1000000 + t.tv_usec - s.tv_usec);

  printf("FORKING\n");
  if (fork()) {
      int env = __envid;
      int child;

      close(readfd);
      close(pfdr[1]);

      printf("PARENT\n");

      if ((shmaddr = (int *) shmat(sid, 0, 0)) < 0) {
	  perror("shmat");
      }
      *shmaddr = 0;

      for (i = 0; i < SIZE; i++) {
	  aarray[i] = 0;
      }

      /* Exchange envids */
      write(writefd, &env, sizeof(env));
      read(pfdr[0], &child, sizeof(child));
      printf("parent: %d child %d\n", env, child);

      printf("YIELD\n");

      gettimeofday(&s, NULL);
      val = 0;
      for (i = 0; i < N; i++) {
	  *shmaddr = val +  1;
	  val += 2;
	  do {
	      yield(child);
	  } while (*shmaddr < val);
      }
      gettimeofday(&t, NULL);
      printf("%d: yield: in %lu usec\n", N, 
	     (t.tv_sec - s.tv_sec) * 1000000 + t.tv_usec - s.tv_usec);

      gettimeofday(&s, NULL);
      for (i = 0; i < N; i++) {
	  *shmaddr = val +  1;
	  val += 2;
	  do {
	      yield(-1);
	  } while (*shmaddr < val);
      }
      gettimeofday(&t, NULL);
      printf("%d: undirected yield: in %lu usec\n", N, 
	     (t.tv_sec - s.tv_sec) * 1000000 + t.tv_usec - s.tv_usec);

      if (shmctl(sid, IPC_RMID, 0)) {
	  perror("shmctl");
      }

      printf("PINGPONG one byte\n");
    
      aarray[0] = 0;

      gettimeofday(&s, NULL);
      for (i = 0; i < N; i++) {
	  write(writefd, &aarray[0], 1);
	  yield(child);
	  read(pfdr[0], &aarray[0], 1);
      }
      gettimeofday(&t, NULL);
      printf("%d: pingpong: %d bytes in %lu usec\n", N, 1, 
	     (t.tv_sec - s.tv_sec) * 1000000 + t.tv_usec - s.tv_usec);

      printf("PINGPONG %d bytes\n", SIZE);

      gettimeofday(&s, NULL);
      for (i = 0; i < N; i++) {
	  write(writefd, &aarray[0], SIZE);
	  read(pfdr[0], &aarray[0], SIZE);
      }
      gettimeofday(&t, NULL);

      printf("%d pingpong: %d bytes in %ld usec\n", N, SIZE, 
	     (t.tv_sec - s.tv_sec) * 1000000 + t.tv_usec - s.tv_usec);
      close(pfdw[0]);

      printf("TESTING HUMONGOUS WRITE TO PIPE\n");
      for (i = 0; i < TESTSZ; i++) {
	  aarray[i] = i % 13;
      }
      
      r = write(writefd, aarray, TESTSZ);
      if (r != TESTSZ) {
	  perror("write");
      }
      printf("write on %d returned %d\n", writefd, r);

      r = write(writefd, aarray, TESTSZ);
      if (r != TESTSZ) {
	  perror("write");
      }
      printf("write on %d returned %d\n", writefd, r);

      printf("DONE\n");
      sleep(20);
      printf("DONE WRITER\n");
      close(writefd);
      printf("CLOSER WRITE FD\n");
  } else {
      int env = __envid;
      int parent; 

      close(writefd);
      close(pfdr[0]);

      printf("CHILD\n");

      if ((shmaddr = (int *) shmat(sid, 0, 0)) < 0) {
	  perror("shmat");
      }
      *shmaddr = 0;

      for (i = 0; i < SIZE; i++) {
	  aarray[i] = 0;
      }

      read(readfd, &parent, sizeof(parent));
      write(pfdr[1], &env, sizeof(env));

      printf("child: %d parent %d\n", env, parent);

      val = 1;
      for (i = 0; i < N; i++) {
	  do {
	      yield(parent);
	  } while (*shmaddr < val);
	  *shmaddr = val + 1;
	  val = val + 2;
      }

      printf("done: %d\n", val);

      for (i = 0; i < N; i++) {
	  do {
	      yield(-1);
	  } while (*shmaddr < val);
	  *shmaddr = val + 1;
	  val = val + 2;
      }
      printf("done: %d\n", val);


      for (i = 0; i < N; i++) {
	  read(readfd, &aarray[0], 1);
	  write(pfdr[1], &aarray[0], 1);
	  yield(parent);
      }

      for (i = 0; i < N; i++) {
	  read(readfd, &aarray[0], SIZE);
	  write(pfdr[1], &aarray[0], SIZE);
      }

      close(pfdr[1]);

      for (i = 0; i < TESTSZ; i++) {
	  aarray[i] = '-';
      }
      aarray[TESTSZ - 1] = 0;

      printf("read returned %d\n",read(readfd, aarray, TESTSZ));
      printf("testting aarray:\n");
      for (i = 0; i < TESTSZ; i++) {
	  if (aarray[i] != i % 13) {
	      printf("differ at offset %d read %d written %d\n",
		     i,(u_int)aarray[i],i % 13);
	      exit(0);
	  }
      }

      for (i = 0; i < TESTSZ; i++) {aarray[i] = '-';}

      printf("reading one by one\n");
      for (i = 0; i < TESTSZ; i++) {
	  if ((status = read(readfd,(char *)&aarray[i],1)) != 1) {
	      printf("read returned %d\n",status);
	      printf("FAILED\n");
	      exit(-1);
	  }
      }
      printf("testting aarray:\n");
      for (i = 0; i < TESTSZ; i++) {
	  if (aarray[i] != i % 13) {
	      printf("differ at offset %d read %d written %d\n",
		     i,(u_int)aarray[i],i % 13);
	  }
				      
      }
      printf("THIS READ SHOULD RETURN 0\n");
      printf("READ: %d\n",read(readfd,aarray,10));
      printf("DONE\n");

  }
  printf("Ok\n");
  return (0);
}
Пример #5
0
int main(int argc, char* argv[]) {

	key_t cle;

	int taille = 0;

	int nb_fils, i;

	if (argc != 2) {
		printf("%derror syntaxe : %s nbProcessus \n", argc, argv[0]);
		exit(1);
	}
	nb_fils = atoi(argv[1]);

	/*------------------------------------------------------*/
	/* creation segment memoir	*/
	/*------------------------------------------------------*/

	taille = (nb_fils + 1) * sizeof(int);

	char code = 0;

	code = getpid() & 255;
	if (code == 0) {
		printf("error code = 0");
		exit(-1);
	}
	if ((cle = ftok(argv[0], code)) == -1) {
		perror("ftok");
		exit(-1);
	}
	if ((shm_id = shmget(cle, taille, IPC_CREAT | 0666)) < 0) {
		perror("shmget");
		exit(-1);
	}

	if ((adr_att = shmat(shm_id, NULL, 0600)) == (void *) -1) {
		perror("shmat");
		exit(-1);
	}
	tab_val_random = (int*) adr_att;
	tab_val_random[0] = 0;

	/*------------------------------------------------------*/
	/* traitement liberation memoir partage	*/
	/*------------------------------------------------------*/
	remonte_partagee(nb_fils);
	while (tab_val_random[0] == 0) {
		printf("attend while %d \n", tab_val_random[0]);
		sleep(1);
	}

	int result = 0;
	for (i = 1; i < nb_fils + 1; i++) {

		printf("shm%d recu %d \n", i, tab_val_random[i]);
		result += tab_val_random[i];
	}
	printf("pere %d : la somme est %d \n", getpid(), result);
	shmdt(adr_att);
	shmctl(shm_id, IPC_RMID, NULL);

	return EXIT_SUCCESS;
}
Пример #6
0
int main(void){

	pid_t pere,pid1,pid2,pid3;
	int msg,i=1;
	//key_t key = ftok(CLE, 'a');


	msg = msgget(CLE,IPC_CREAT|IPC_EXCL | 0600);
	if(msg == -1){
		perror("Probleme avec la file");
	}

	pere = getpid();
	while(pere == getpid() && i<4){
		
		if(fork()==0){


			printf("Processus %i cree\n",i);
			message m;
			strcpy(m.data,"je suis le process ");
			char tmp[2];
			sprintf(tmp,"%d",i);
			strcat(m.data,tmp);
			m.mtype = 5;

			msgsnd(msg,&m,1000,IPC_NOWAIT);
			
			int mymemory;
			mymemory = shmget(IPC_PRIVATE,sizeof(char),0666);

			char* c = (char*) shmat(mymemory,NULL,0);
			
			cleMemoire cm;
			

			if(i>1){
			cm.id = i -1;
			cm.cle = mymemory;
			strcpy(cm.data,m.data);
			printf("Je suis %i et j'envoie à %i\n",i,(int)cm.id);
			msgsnd(msg,&cm,1000,0);
			}
			if(i<3){
			msgrcv(msg,&cm,1000,i,0);
			printf("Je suis %i et j'ai recu : %s\n",i,cm.data);
			}
			shmdt(c);
			shmctl(mymemory,IPC_RMID,NULL);

			printf("JE MEURS %i\n",i);
			exit(0);
		}
		i++;
	}
		message m;

		for(i=1;i<4;i++) wait(NULL);
		for(i=1;i<4;i++){
			//printf("Je lis %i\n",i);
			msgrcv(msg,&m,1000,5,0);
			printf("%s\n",m.data);
			//printf("J'ai lu %i\n",i);
		}
		msgctl(msg,IPC_RMID,0);
		printf("Je m'en vais, bisous\n");
		return 0;

}
Пример #7
0
GimpPlugInShm *
gimp_plug_in_shm_new (void)
{
  /* allocate a piece of shared memory for use in transporting tiles
   *  to plug-ins. if we can't allocate a piece of shared memory then
   *  we'll fall back on sending the data over the pipe.
   */

  GimpPlugInShm *shm = g_slice_new0 (GimpPlugInShm);

  shm->shm_ID = -1;

#if defined(USE_SYSV_SHM)

  /* Use SysV shared memory mechanisms for transferring tile data. */
  {
    shm->shm_ID = shmget (IPC_PRIVATE, TILE_MAP_SIZE, IPC_CREAT | 0600);

    if (shm->shm_ID != -1)
      {
        shm->shm_addr = (guchar *) shmat (shm->shm_ID, NULL, 0);

        if (shm->shm_addr == (guchar *) -1)
          {
            g_printerr ("shmat() failed: %s\n" ERRMSG_SHM_DISABLE,
                        g_strerror (errno));
            shmctl (shm->shm_ID, IPC_RMID, NULL);
            shm->shm_ID = -1;
          }

#ifdef IPC_RMID_DEFERRED_RELEASE
        if (shm->shm_addr != (guchar *) -1)
          shmctl (shm->shm_ID, IPC_RMID, NULL);
#endif
      }
    else
      {
        g_printerr ("shmget() failed: %s\n" ERRMSG_SHM_DISABLE,
                    g_strerror (errno));
      }
  }

#elif defined(USE_WIN32_SHM)

  /* Use Win32 shared memory mechanisms for transferring tile data. */
  {
    gint  pid;
    gchar fileMapName[MAX_PATH];

    /* Our shared memory id will be our process ID */
    pid = GetCurrentProcessId ();

    /* From the id, derive the file map name */
    g_snprintf (fileMapName, sizeof (fileMapName), "GIMP%d.SHM", pid);

    /* Create the file mapping into paging space */
    shm->shm_handle = CreateFileMapping (INVALID_HANDLE_VALUE, NULL,
                                         PAGE_READWRITE, 0,
                                         TILE_MAP_SIZE,
                                         fileMapName);

    if (shm->shm_handle)
      {
        /* Map the shared memory into our address space for use */
        shm->shm_addr = (guchar *) MapViewOfFile (shm->shm_handle,
                                                  FILE_MAP_ALL_ACCESS,
                                                  0, 0, TILE_MAP_SIZE);

        /* Verify that we mapped our view */
        if (shm->shm_addr)
          {
            shm->shm_ID = pid;
          }
        else
          {
            g_printerr ("MapViewOfFile error: %d... " ERRMSG_SHM_DISABLE,
                        GetLastError ());
          }
      }
    else
      {
        g_printerr ("CreateFileMapping error: %d... " ERRMSG_SHM_DISABLE,
                    GetLastError ());
      }
  }

#elif defined(USE_POSIX_SHM)

  /* Use POSIX shared memory mechanisms for transferring tile data. */
  {
    gint  pid;
    gchar shm_handle[32];
    gint  shm_fd;

    /* Our shared memory id will be our process ID */
    pid = gimp_get_pid ();

    /* From the id, derive the file map name */
    g_snprintf (shm_handle, sizeof (shm_handle), "/gimp-shm-%d", pid);

    /* Create the file mapping into paging space */
    shm_fd = shm_open (shm_handle, O_RDWR | O_CREAT, 0600);

    if (shm_fd != -1)
      {
        if (ftruncate (shm_fd, TILE_MAP_SIZE) != -1)
          {
            /* Map the shared memory into our address space for use */
            shm->shm_addr = (guchar *) mmap (NULL, TILE_MAP_SIZE,
                                             PROT_READ | PROT_WRITE, MAP_SHARED,
                                             shm_fd, 0);

            /* Verify that we mapped our view */
            if (shm->shm_addr != MAP_FAILED)
              {
                shm->shm_ID = pid;
              }
            else
              {
                g_printerr ("mmap() failed: %s\n" ERRMSG_SHM_DISABLE,
                            g_strerror (errno));

                shm_unlink (shm_handle);
              }
          }
        else
          {
            g_printerr ("ftruncate() failed: %s\n" ERRMSG_SHM_DISABLE,
                        g_strerror (errno));

            shm_unlink (shm_handle);
          }

        close (shm_fd);
      }
    else
      {
        g_printerr ("shm_open() failed: %s\n" ERRMSG_SHM_DISABLE,
                    g_strerror (errno));
      }
  }

#endif

  if (shm->shm_ID == -1)
    {
      g_slice_free (GimpPlugInShm, shm);
      shm = NULL;
    }
  else
    {
      GIMP_LOG (SHM, "attached shared memory segment ID = %d", shm->shm_ID);
    }

  return shm;
}
Пример #8
0
int main(){

	  /************DICHIARAZIONE DELLE VARIABILI***************/

     int id_sem,id_shared,k;
     key_t chiave=IPC_PRIVATE;
     key_t c_sem=IPC_PRIVATE;
     int status;
     Buffer *ptr_sh;

     pid_t pid;
     int num_processi=10;

  /************RICHIESTA DEL SEGMENTO DI MEMORIA CONDIVISA***********/


     id_shared=shmget(chiave,sizeof(Buffer),IPC_CREAT|0664);
     printf(" id_shared=%d \n",id_shared);
     ptr_sh=(Buffer*) (shmat(id_shared,0,0));

//   Inzializzazione struttura dati
     ptr_sh->numlettori=0;
     ptr_sh->numscrittori=0;
     ptr_sh->messaggio=0;	


//   richiesta dei semafori
     id_sem=semget(c_sem,4,IPC_CREAT|0664);

//   inizializzazione
     semctl(id_sem,SYNCH,SETVAL,1);
     semctl(id_sem,MUTEXL,SETVAL,1);
     semctl(id_sem,MUTEXS,SETVAL,1);
     semctl(id_sem,MUTEX,SETVAL,1);



  /****GENERAZIONE DEI PROCESSI E OPERAZIONI DI R/W****/


    //generazione di scrittori e lettori
     for (k=0;k<num_processi;k++) {

	pid=fork();

	if (pid==0)  {                //processo figlio
	  if ( (k%2)==0) {
	     printf("sono il figlio scrittore. Il mio pid %d \n",getpid());
	     Scrittore(id_sem,ptr_sh);
          }else {
             printf("sono il figlio lettore. Il mio pid %d \n",getpid());
             Lettore(id_sem,ptr_sh);
          } 
          exit(0);
	} 
     }


     for (k=0; k<num_processi;k++){
       pid=wait(&status);
       if (pid==-1)
		perror("errore");
	else
		 printf ("Figlio n.ro %d e\' morto con status= %d \n ",pid,status);
     }
     shmctl(id_shared,IPC_RMID,0);
     semctl(id_sem,0,IPC_RMID);

     return 1;

}
Пример #9
0
XCODE_IPC_DESCR_T *xcode_ipc_open(unsigned int sz, key_t key) {
  XCODE_IPC_DESCR_T *pIpc = NULL;
  struct shmid_ds buf;
  int shmid;
  //int rc;
#ifdef __linux__
  int flags = 0x180;
#else
  int flags = SEM_R | SEM_A;
#endif // __linux__

  buf.shm_segsz = 0;
  if((shmid = shmget(key, 0, flags)) != -1) {
    // get the segment size of any existing shm
    if(shmctl(shmid, IPC_STAT, &buf) != 0) {
      return NULL;
    }
  }

  if(buf.shm_segsz == 0) {
    LOG(X_ERROR("xcode shared mem not yet created by writer"));
    return NULL;
  }

  if(buf.shm_segsz < sz) {
    LOG(X_ERROR("xcode shared mem size %d below minimum %d"), buf.shm_segsz, sz);
    return NULL;
  }

  pIpc = avc_calloc(1, sizeof(XCODE_IPC_DESCR_T));
  pIpc->key = key;
  pIpc->sz = sz;

  if((pIpc->shmid = shmget(pIpc->key, pIpc->sz, flags)) == -1) {
    LOG(X_ERROR("xcode shmget failed for key: 0x%x flags: 0x%x size: %u"), 
                pIpc->key, flags, pIpc->sz);
    free(pIpc);
    return NULL;
  }

  if(shmctl(pIpc->shmid, IPC_STAT, &buf) != 0) {
    LOG(X_ERROR("xcode shmctl failed for shmid %d"), pIpc->shmid);
    free(pIpc);
    return NULL;
  }

  if(buf.shm_nattch > 1) {
    LOG(X_ERROR("xcode shared mem already has %d attached"), buf.shm_nattch);
    free(pIpc);
    return NULL;
  }

  if((pIpc->pmem = shmat(pIpc->shmid, 0, 0)) == (void *) -1) {
    LOG(X_ERROR("xcode shmat failed"));
    free(pIpc);
    return NULL;
  }

  if((pIpc->sem_srv = sem_open(XCODE_IPC_SEM_NAME_SRV, 0,
                        S_IRWXU | S_IRWXG | S_IRWXO , 0)) == SEM_FAILED) {
    LOG(X_ERROR("xcode sem_open server failed with "ERRNO_FMT_STR), ERRNO_FMT_ARGS);
    pIpc->sem_srv = NULL;
    return NULL;
  }

  if((pIpc->sem_cli = sem_open(XCODE_IPC_SEM_NAME_CLI, 0,
                        S_IRWXU | S_IRWXG | S_IRWXO , 0)) == SEM_FAILED) {
    LOG(X_ERROR("xcode sem_open client failed with "ERRNO_FMT_STR), ERRNO_FMT_ARGS);
    pIpc->sem_cli = NULL;
    return NULL;
  }

  pIpc->pmem->hdr.cmd = XCODE_IPC_CMD_NONE;

  //fprintf(stderr, "init ipc ok\n");

  return pIpc;
}
Пример #10
0
int P_shmctl(int shmid, int cmd, struct shmid_ds *buf) { return shmctl(shmid, cmd, buf); }
Пример #11
0
Bool
dfb_x11_open_window( DFBX11 *x11, XWindow** ppXW, int iXPos, int iYPos, int iWidth, int iHeight, DFBSurfacePixelFormat format )
{
     XWindow              *xw;
     XSetWindowAttributes  attr = { .background_pixmap = 0 };
     void                 *old_error_handler = 0;
     unsigned int          cw_mask = CWEventMask;

     D_DEBUG_AT( X11_Window, "Creating %4dx%4d %s window...\n", iWidth, iHeight, dfb_pixelformat_name(format) );

     xw = D_CALLOC( 1, sizeof(XWindow) );
     if (!xw)
          return D_OOM();

     /* We set the structure as needed for our window */
     xw->width   = iWidth;
     xw->height  = iHeight;
     xw->display = x11->display;

     xw->screenptr = DefaultScreenOfDisplay(xw->display);
     xw->screennum = DefaultScreen(xw->display);
     xw->depth     = DefaultDepthOfScreen( xw->screenptr );
     xw->visual    = DefaultVisualOfScreen( xw->screenptr );

     attr.event_mask =
            ButtonPressMask
          | ButtonReleaseMask
          | PointerMotionMask
          | KeyPressMask
          | KeyReleaseMask
          | ExposureMask
          | StructureNotifyMask;

     if (dfb_config->x11_borderless) {
          attr.override_redirect = True;

          cw_mask |= CWOverrideRedirect;
     }

     XLockDisplay( x11->display );

     old_error_handler = XSetErrorHandler( error_handler );

     error_code = 0;

     xw->window = XCreateWindow( xw->display,
                                 RootWindowOfScreen(xw->screenptr),
                                 iXPos, iYPos, iWidth, iHeight, 0, xw->depth, InputOutput,
                                 xw->visual, cw_mask, &attr );
     XSync( xw->display, False );
     if (!xw->window || error_code) {
          D_FREE( xw );
          XUnlockDisplay( x11->display );
          return False;
     }


     XSizeHints Hints;

     /*
      * Here we inform the function of what we are going to change for the
      * window (there's also PPosition but it's obsolete)
      */
     Hints.flags    =    PSize | PMinSize | PMaxSize;

     /*
      * Now we set the structure to the values we need for width & height.
      * For esthetic reasons we set Width=MinWidth=MaxWidth.
      * The same goes for Height. You can try whith differents values, or
      * let's use Hints.flags=Psize; and resize your window..
      */
     Hints.min_width          =    Hints.max_width          =    Hints.base_width    =    xw->width;
     Hints.min_height    =    Hints.max_height    =    Hints.base_height   =    xw->height;

     /* Now we can set the size hints for the specified window */
     XSetWMNormalHints(xw->display,xw->window,&Hints);

     /* We change the title of the window (default:Untitled) */
     XStoreName(xw->display,xw->window,"DFB X11 system window");

     xw->gc = XCreateGC(xw->display, xw->window, 0, NULL);

#if 0
     // Create a null cursor
     Pixmap  pixmp1;
     Pixmap  pixmp2;
     XColor  fore;
     XColor  back;
     char    zero = 0;

     pixmp1 = XCreateBitmapFromData( xw->display, xw->window, &zero, 1, 1 );
     pixmp2 = XCreateBitmapFromData( xw->display, xw->window, &zero, 1, 1 );

     xw->NullCursor = XCreatePixmapCursor( xw->display, pixmp1, pixmp2, &fore, &back, 0, 0 );

     XFreePixmap ( xw->display, pixmp1 );
     XFreePixmap ( xw->display, pixmp2 );

     XDefineCursor( xw->display, xw->window, xw->NullCursor );
#endif

     /* maps the window and raises it to the top of the stack */
     XMapRaised( xw->display, xw->window );


     if (x11->use_shm) {
          // Shared memory
          xw->shmseginfo=(XShmSegmentInfo *)D_CALLOC(1, sizeof(XShmSegmentInfo));
          if (!xw->shmseginfo) {
               x11->use_shm = false;
               goto no_shm;
          }

          xw->ximage=XShmCreateImage(xw->display, xw->visual, xw->depth, ZPixmap,
                                     NULL,xw->shmseginfo, xw->width, xw->height * 2);
          XSync( xw->display, False );
          if (!xw->ximage || error_code) {
               D_ERROR("X11: Error creating shared image (XShmCreateImage) \n");
               x11->use_shm = false;
               D_FREE(xw->shmseginfo);
               error_code = 0;
               goto no_shm;
          }

          xw->bpp = (xw->ximage->bits_per_pixel + 7) / 8;

          /* we firstly create our shared memory segment with the size we need, and
          correct permissions for the owner, the group and the world --> 0777 */
          xw->shmseginfo->shmid=shmget(IPC_PRIVATE,
                                       xw->ximage->bytes_per_line * xw->ximage->height * 2,
                                       IPC_CREAT|0777);

          if (xw->shmseginfo->shmid<0) {
               x11->use_shm = false;
               XDestroyImage(xw->ximage);
               D_FREE(xw->shmseginfo);
               goto no_shm;
          }

          /* Then, we have to attach the segment to our process, and we let the
          function search the correct memory place --> NULL. It's safest ! */
          xw->shmseginfo->shmaddr = shmat( xw->shmseginfo->shmid, NULL, 0 );
          if (!xw->shmseginfo->shmaddr) {
               x11->use_shm = false;
               shmctl(xw->shmseginfo->shmid,IPC_RMID,NULL);
               XDestroyImage(xw->ximage);
               D_FREE(xw->shmseginfo);
               goto no_shm;
          }

          /* We set the buffer in Read and Write mode */
          xw->shmseginfo->readOnly=False;

          xw->virtualscreen= xw->ximage->data = xw->shmseginfo->shmaddr;


          XSetErrorHandler( error_handler_shm );

          XShmAttach(x11->display,xw->shmseginfo);

          XShmPutImage(x11->display, xw->window, xw->gc, xw->ximage,
                       0, 0, 0, 0, 1, 1, False);

          XSync(x11->display, False);

          XSetErrorHandler( error_handler );

          if (!x11->use_shm) {
               shmdt(xw->shmseginfo->shmaddr);
               shmctl(xw->shmseginfo->shmid,IPC_RMID,NULL);
               XDestroyImage(xw->ximage);
               D_FREE(xw->shmseginfo);
          }
     }

no_shm:
     if (!x11->use_shm) {
          int pitch;

          xw->bpp = (xw->depth > 16) ? 4 :
                    (xw->depth >  8) ? 2 : 1;

          pitch = (xw->bpp * xw->width + 3) & ~3;

          /* Use malloc(), not D_MALLOC() here, because XCreateImage()
           * will call free() on this data.
           */
          xw->virtualscreen = malloc ( 2 * xw->height * pitch );

          xw->ximage = XCreateImage( xw->display, xw->visual, xw->depth, ZPixmap, 0,
                                     xw->virtualscreen, xw->width, xw->height * 2, 32, pitch );
          XSync( xw->display, False );
          if (!xw->ximage || error_code) {
               D_ERROR( "X11/Window: XCreateImage( Visual %02lu, depth %d, size %dx%d, buffer %p [%d] ) failed!\n",
                        xw->visual->visualid, xw->depth, xw->width, xw->height * 2, xw->virtualscreen, pitch );
               XFreeGC(xw->display,xw->gc);
               XDestroyWindow(xw->display,xw->window);
               XSetErrorHandler( old_error_handler );
               XUnlockDisplay( x11->display );
               D_FREE( xw );
               return False;
          }
     }

     XSetErrorHandler( old_error_handler );

     XUnlockDisplay( x11->display );

     D_INFO( "X11/Display: %ssing XShm.\n", x11->use_shm ? "U" : "Not u" );

     (*ppXW) = xw;

     return True;
}

void
dfb_x11_close_window( DFBX11 *x11, XWindow* xw )
{
     if (x11->use_shm) {
          XShmDetach( xw->display, xw->shmseginfo );
          shmdt( xw->shmseginfo->shmaddr );
          shmctl( xw->shmseginfo->shmid, IPC_RMID, NULL );
          D_FREE( xw->shmseginfo );
     }

     XDestroyImage( xw->ximage );

     XFreeGC( xw->display, xw->gc );
     XDestroyWindow( xw->display, xw->window );
#if 0
     XFreeCursor( xw->display, xw->NullCursor );
#endif

     D_FREE( xw );
}
Пример #12
0
void * CBUShm::Open(const char *name, int shmsize)
{
   char buf[256];
   Close();
   sprintf(buf,"%s.shm",name);
   m_fileno = sh_open(buf,O_CREAT|O_RDWR,SH_DENYNO);
   if (m_fileno==-1)
   {
      sprintf(m_szmsg,"Cannot open SHM File for '%s' size=%d",name,shmsize);
      return(NULL);
   }
#ifdef WIN32
   int i;
   for (i=0;i<sizeof(buf);i++)
   {
      if ('\\'==buf[i])
         buf[i]='_';
      else if (0==buf[i])
         break;
   }
   if (shmsize>0)
   {
      m_shmid = CreateFileMapping(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,0,shmsize,(LPCSTR)buf);
      if (m_shmid==NULL)
      {
         // 共享内存创建错误:
         sprintf(m_szmsg,"Cannot open share memory for SHM(%s) size=%d -errno:%u!",buf,shmsize,GetLastError());
         Close();
         return(NULL);
      }
   }
   else
   {
      m_shmid = OpenFileMapping(FILE_MAP_WRITE|FILE_MAP_READ,FALSE,(LPCSTR)buf);
      if (m_shmid==NULL)
      {
         sprintf(m_szmsg,"Cannot open share memory for SHM(%s) - errno:%u!",buf,GetLastError());
         Close();
         return(NULL);
      }
   }
   m_address = MapViewOfFile(m_shmid,FILE_MAP_WRITE|FILE_MAP_READ,0,0,0);
   if (m_address==NULL)
   {
      sprintf(m_szmsg,"MapViewOfFile fail [SHM(%s) size=%d] - errno:%u!",buf,shmsize,GetLastError());
      Close();
      return(NULL);
   }
   BY_HANDLE_FILE_INFORMATION finfo;
   GetFileInformationByHandle(m_shmid,&finfo);
   m_size = finfo.nFileSizeLow;
   return(m_address);
#else
   bool bcreated = true;
   key_t shmkey = myftok(buf,BUSHM_KID);
   if (shmsize>0)
   {
      m_shmid = shmget(shmkey,shmsize,SHM_RIGHT|IPC_CREAT);
   }
   else
      m_shmid = -1;
   if (m_shmid==-1)
   {
      m_shmid = shmget(shmkey,0,BUSHM_FLAG);
      bcreated = false;
   }
   if (m_shmid==-1)
   {
      // 共享内存创建错误:
      sprintf(m_szmsg,"Cannot open share memory for key:0x%X-errno:%d!",shmkey,errno);
      Close();
      return(NULL);
   }
   m_address = shmat(m_shmid,0,0);
#ifdef SHM_FAILED //11:50 2006-7-4 for HP_UX64 
   if (m_address==SHM_FAILED)
#else
   if (m_address==(void *)-1L)
#endif
   {
      m_address = NULL;
      // 则表示挂接的地址出现问题,可能属于flag不正确的缘故
      sprintf(m_szmsg,"shmkey=%x:shmat(%d,0,0) 返回错误errno=%d!",shmkey,m_shmid,errno);
      Close();
      if (bcreated)
         Remove(name);
   }
   struct shmid_ds info;
   shmctl(m_shmid,IPC_STAT,&info);
   m_size = info.shm_segsz;
   return(m_address);
#endif
}
Пример #13
0
/*---------------------------------------------------------------------+
|                               main                                   |
| ==================================================================== |
|                                                                      |
|                                                                      |
| Function:  Main program  (see prolog for more details)               |
|                                                                      |
| Returns:   (0)  Successful completion                                |
|            (-1) Error occurred                                       |
|                                                                      |
+---------------------------------------------------------------------*/
int main(int argc, char **argv)
{
	int i;

	int shmid[MAX_SHMEM_NUMBER];	/* (Unique) Shared memory identifier */

	char *shmptr[MAX_SHMEM_NUMBER];	/* Shared memory segment address */
	char *ptr;		/* Index into shared memory segment */

	int value = 0;		/* Value written into shared memory segment */

	key_t mykey[MAX_SHMEM_NUMBER];
	char *null_file = "/dev/null";
	char proj[MAX_SHMEM_NUMBER] = {
		'3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'E'
	};

	/*
	 * Parse command line arguments and print out program header
	 */
	parse_args(argc, argv);
	printf("%s: IPC Shared Memory TestSuite program\n", *argv);

	for (i = 0; i < offsets_cnt; i++) {
		char tmpstr[256];
		/*
		 * Create a key to uniquely identify the shared segment
		 */

		mykey[i] = ftok(null_file, proj[i]);

		printf
		    ("\n\tmykey to uniquely identify the shared memory segment 0x%x\n",
		     mykey[i]);

		printf("\n\tGet shared memory segment (%d bytes)\n",
		       shmem_size);
		/*
		 * Obtain a unique shared memory identifier with shmget ().
		 */

		if ((long)
		    (shmid[i] =
		     shmget(mykey[i], shmem_size, IPC_CREAT | 0666)) < 0)
			sys_error("shmget failed", __LINE__);

		printf("\n\tAttach shared memory segment to process\n");

		if ((long)(shmptr[i] = shmat(shmid[i], NULL, 0)) == -1) {
			/* If shmat(2) failed, we need the currect process address
			   space layout to debug. The failure can be random. */
			sprintf(tmpstr, "cat /proc/%d/maps >&2", (int)getpid());
			fprintf(stderr, "heap %p\n", sbrk(0));
			system(tmpstr);

			sprintf(tmpstr, "shmat failed - return: %ld",
				(long)shmptr[i]);
			sys_error(tmpstr, __LINE__);
		}

		printf("\n\tShared memory segment address : %p \n", shmptr[i]);

		printf("\n\tIndex through shared memory segment ...\n");

		/*
		 * Index through the shared memory segment
		 */

		for (ptr = shmptr[i]; ptr < (shmptr[i] + shmem_size); ptr++)
			*ptr = value++;

	}			// for 1..11

	printf("\n\tDetach from the segment using the shmdt subroutine\n");

	printf("\n\tRelease shared memory\n");

	for (i = 0; i < offsets_cnt; i++) {
		// Detach from the segment

		shmdt(shmptr[i]);

		// Release shared memory

		if (shmctl(shmid[i], IPC_RMID, 0) < 0)
			sys_error("shmctl failed", __LINE__);

	}			// 2nd for 1..11
	/*
	 * Program completed successfully -- exit
	 */

	printf("\nsuccessful!\n");

	return (0);

}
Пример #14
0
int main(int argc, char* argv[]){
	int numchildren;
	long long MaxVal;
	
	
	if (argc != 3){
		printf("Not the right number of command line arguments\n");
		printf("exiting\n");
		return 0;
	}
	else {	//argc == 3
		numchildren = atoi(argv[1]);
		MaxVal = atoll(argv[2]);
	}
	
	printf("\nMAXVAL == %lld\n", MaxVal);



	key_t key;
	int shmid;
	if ( (key = ftok("mykey.txt", 'p')) == (key_t) -1){
		perror("ftok");
		return -1;
	}

	shmid = shmget(key, sizeof(threeIntegers), 0644 | IPC_CREAT);
	if(shmid < 0){
		perror("shmget");
		return -1;
	}
	
//	printf("shmid: %d\n", shmid);
	char * data;
	data = shmat(shmid, (void *)0, 0);
	if(data < 0){
		perror("shmat");
		return -1;
	}

	threeIntegers *aa = (threeIntegers *) data;
	
	aa->firstnum = 1;
	aa->secondnum = 2;
	aa->winnerpid = 0;
	sem_init(&(aa->sema), 1, 1);
	sem_init(&(aa->childlock), 1, 1);
	aa->childcounter = 0;
	
	aa->AllKidsReady = 0;


	int pid = 1;//parent pid >0
	int i;
	for(i=0; i<numchildren; i++){ //makes cval # of kids, only the parent will do it, it checks pid, kids =0
		if(pid>0){
			if ((pid = fork()) < 0) { 
				fprintf(stderr, "fork failed\n"); 
				exit(1); 
			}
			
			if(pid > 0){
				printf("\nParent created %d\n", pid);
			}
			
		}
	}

	//the child	 
	if (pid == 0)
	{
		printf("\t\t\tchildpid = %d\n", getpid());
		long long tmp1 = 0;
		long long tmp2 = 0;
		long long tmp3 = 0;
		
		sem_wait(&(aa->childlock));
			aa->childcounter = aa->childcounter + 1;
		sem_post(&(aa->childlock));
		
		int akir = aa->AllKidsReady;
		while(akir == 0){
			//printf("%d: kids not all ready\n", getpid());
			sched_yield();
			akir = aa->AllKidsReady;
		}
		
		//bool bl = true;
		while(1)
		{
			while ( sem_trywait(&(aa->sema)) < 0 ) {
				if( errno == EAGAIN)
					continue;
				else perror("trywait error");
			}
				printf("pid = %d: ENGAGED\n", getpid());
			
				tmp1 = aa->firstnum;
				tmp2 = aa->secondnum;
				if( (tmp1 > MaxVal) || (tmp2 > MaxVal) )
				{
					printf("first if, tmp1 = %lld, tmp2 = %lld\n", tmp1, tmp2);
					sem_post(&(aa->sema));
					exit(0);
				}

				tmp3 = tmp1 + tmp2;

				if(tmp1 <= tmp2)
				{
					printf("second if, tmp1 = %lld, tmp2 = %lld\n", tmp1, tmp2);
					aa->firstnum = tmp3;
				}
				else //tmp1 > tmp2
				{
					printf("third if, tmp1 = %lld, tmp2 = %lld\n", tmp1, tmp2);
					aa->secondnum = tmp3;
				}


				if(tmp3 > MaxVal)
				{
					printf("fourth if, tmp1 = %lld, tmp2 = %lld\n", tmp1, tmp2);
					aa->winnerpid = getpid();
				}
			
			sem_post(&(aa->sema));
			//printf("\n");
			sched_yield();
			
			
			
		}
	}

	//the Parent
	else {
		while(numchildren != aa->childcounter){
			continue;
		}
	
		printf("\n\nPARENT UNLOCKS THE WORLD\n\n");
		aa->AllKidsReady = 1;
		
		for(i=0; i<numchildren; i++){
			wait(NULL);
		}
		
		sem_wait(&(aa->sema));
			printf("\n\nThe winner has pid: %d\n", aa->winnerpid);
		sem_post(&(aa->sema));
		sem_destroy(&(aa->sema));
		
		int d = shmctl(shmid, IPC_RMID, NULL);
		if(d<0){
			perror("shmctl");
			return -1;
		}
		
		return 0;
	}

	return 0;
}
Пример #15
0
static int parse_testcase()
{
    int i, j, mainkey_cnt;
    struct testcase_base_info *info;
    char mainkey_name[32], display_name[64], binary[16];
    int activated, category, run_type;
    int len;

    mainkey_cnt = script_mainkey_cnt();
    info = malloc(sizeof(struct testcase_base_info) * mainkey_cnt);
    if (info == NULL) {
        db_error("core: allocate memory for temporary test case basic "
                "information failed(%s)\n", strerror(errno));
        return -1;
    }
    memset(info, 0, sizeof(struct testcase_base_info) * mainkey_cnt);

    for (i = 0, j = 0; i < mainkey_cnt; i++) {
        memset(mainkey_name, 0, 32);
        script_mainkey_name(i, mainkey_name);

        if (script_fetch(mainkey_name, "display_name", (int *)display_name, 16))
            continue;

        if (script_fetch(mainkey_name, "activated", &activated, 1))
            continue;

        if (display_name[0] && activated == 1) {
            strncpy(info[j].name, mainkey_name, 32);
            strncpy(info[j].display_name, display_name, 64);
            info[j].activated = activated;

            if (script_fetch(mainkey_name, "program", (int *)binary, 4) == 0) {
                strncpy(info[j].binary, binary, 16);
            }

            info[j].id = j;

            if (script_fetch(mainkey_name, "category", &category, 1) == 0) {
                info[j].category = category;
            }

            if (script_fetch(mainkey_name, "run_type", &run_type, 1) == 0) {
                info[j].run_type = run_type;
            }

            j++;
        }
    }
    total_testcases = j;

    db_msg("core: total test cases #%d\n", total_testcases);
    if (total_testcases == 0) {
        return 0;
    }

    len = sizeof(struct testcase_base_info) * total_testcases;
    base_info_shmid = shmget(IPC_PRIVATE, len, IPC_CREAT | 0666);
    if (base_info_shmid == -1) {
        db_error("core: allocate share memory segment for test case basic "
                "information failed(%s)\n", strerror(errno));
        return -1;
    }

    base_info = shmat(base_info_shmid, 0, 0);
    if (base_info == (void *)-1) {
        db_error("core: attach the share memory for test case basic "
                "information failed(%s)\n", strerror(errno));
        shmctl(base_info_shmid, IPC_RMID, 0);
        return -1;
    }
    memcpy(base_info, info, sizeof(struct testcase_base_info) * 
            total_testcases);

    return total_testcases;
}
Пример #16
0
static void xf_process_tsmf_video_frame_event(xfInfo* xfi, RDP_VIDEO_FRAME_EVENT* vevent)
{
	int i;
	BYTE* data1;
	BYTE* data2;
	UINT32 pixfmt;
	UINT32 xvpixfmt;
	BOOL converti420yv12 = FALSE;
	XvImage * image;
	int colorkey = 0;
	XShmSegmentInfo shminfo;
	xfXvContext* xv = (xfXvContext*) xfi->xv_context;

	if (xv->xv_port == 0)
		return;

	/* In case the player is minimized */
	if (vevent->x < -2048 || vevent->y < -2048 || vevent->num_visible_rects <= 0)
		return;

	if (xv->xv_colorkey_atom != None)
	{
		XvGetPortAttribute(xfi->display, xv->xv_port, xv->xv_colorkey_atom, &colorkey);
		XSetFunction(xfi->display, xfi->gc, GXcopy);
		XSetFillStyle(xfi->display, xfi->gc, FillSolid);
		XSetForeground(xfi->display, xfi->gc, colorkey);
		for (i = 0; i < vevent->num_visible_rects; i++)
		{
			XFillRectangle(xfi->display, xfi->window->handle, xfi->gc,
				vevent->x + vevent->visible_rects[i].x,
				vevent->y + vevent->visible_rects[i].y,
				vevent->visible_rects[i].width,
				vevent->visible_rects[i].height);
		}
	}
	else
	{
		XSetClipRectangles(xfi->display, xfi->gc, vevent->x, vevent->y,
			(XRectangle*) vevent->visible_rects, vevent->num_visible_rects, YXBanded);
	}

	pixfmt = vevent->frame_pixfmt;

	if (xf_tsmf_is_format_supported(xv, pixfmt))
	{
		xvpixfmt = pixfmt;
	}
	else if (pixfmt == RDP_PIXFMT_I420 && xf_tsmf_is_format_supported(xv, RDP_PIXFMT_YV12))
	{
		xvpixfmt = RDP_PIXFMT_YV12;
		converti420yv12 = TRUE;
	}
	else if (pixfmt == RDP_PIXFMT_YV12 && xf_tsmf_is_format_supported(xv, RDP_PIXFMT_I420))
	{
		xvpixfmt = RDP_PIXFMT_I420;
		converti420yv12 = TRUE;
	}
	else
	{
		DEBUG_XV("pixel format 0x%X not supported by hardware.", pixfmt);
		return;
	}

	image = XvShmCreateImage(xfi->display, xv->xv_port,
		xvpixfmt, 0, vevent->frame_width, vevent->frame_height, &shminfo);

	if (xv->xv_image_size != image->data_size)
	{
		if (xv->xv_image_size > 0)
		{
			shmdt(xv->xv_shmaddr);
			shmctl(xv->xv_shmid, IPC_RMID, NULL);
		}
		xv->xv_image_size = image->data_size;
		xv->xv_shmid = shmget(IPC_PRIVATE, image->data_size, IPC_CREAT | 0777);
		xv->xv_shmaddr = shmat(xv->xv_shmid, 0, 0);
	}
	shminfo.shmid = xv->xv_shmid;
	shminfo.shmaddr = image->data = xv->xv_shmaddr;
	shminfo.readOnly = FALSE;

	if (!XShmAttach(xfi->display, &shminfo))
	{
		XFree(image);
		DEBUG_XV("XShmAttach failed.");
		return;
	}

	/* The video driver may align each line to a different size
	   and we need to convert our original image data. */
	switch (pixfmt)
	{
		case RDP_PIXFMT_I420:
		case RDP_PIXFMT_YV12:
			/* Y */
			if (image->pitches[0] == vevent->frame_width)
			{
				memcpy(image->data + image->offsets[0],
					vevent->frame_data,
					vevent->frame_width * vevent->frame_height);
			}
			else
			{
				for (i = 0; i < vevent->frame_height; i++)
				{
					memcpy(image->data + image->offsets[0] + i * image->pitches[0],
						vevent->frame_data + i * vevent->frame_width,
						vevent->frame_width);
				}
			}
			/* UV */
			/* Conversion between I420 and YV12 is to simply swap U and V */
			if (converti420yv12 == FALSE)
			{
				data1 = vevent->frame_data + vevent->frame_width * vevent->frame_height;
				data2 = vevent->frame_data + vevent->frame_width * vevent->frame_height +
					vevent->frame_width * vevent->frame_height / 4;
			}
			else
			{
				data2 = vevent->frame_data + vevent->frame_width * vevent->frame_height;
				data1 = vevent->frame_data + vevent->frame_width * vevent->frame_height +
					vevent->frame_width * vevent->frame_height / 4;
				image->id = pixfmt == RDP_PIXFMT_I420 ? RDP_PIXFMT_YV12 : RDP_PIXFMT_I420;
			}
			if (image->pitches[1] * 2 == vevent->frame_width)
			{
				memcpy(image->data + image->offsets[1],
					data1,
					vevent->frame_width * vevent->frame_height / 4);
				memcpy(image->data + image->offsets[2],
					data2,
					vevent->frame_width * vevent->frame_height / 4);
			}
			else
			{
				for (i = 0; i < vevent->frame_height / 2; i++)
				{
					memcpy(image->data + image->offsets[1] + i * image->pitches[1],
						data1 + i * vevent->frame_width / 2,
						vevent->frame_width / 2);
					memcpy(image->data + image->offsets[2] + i * image->pitches[2],
						data2 + i * vevent->frame_width / 2,
						vevent->frame_width / 2);
				}
			}
			break;

		default:
			memcpy(image->data, vevent->frame_data, image->data_size <= vevent->frame_size ?
				image->data_size : vevent->frame_size);
			break;
	}

	XvShmPutImage(xfi->display, xv->xv_port, xfi->window->handle, xfi->gc, image,
		0, 0, image->width, image->height,
		vevent->x, vevent->y, vevent->width, vevent->height, FALSE);
	if (xv->xv_colorkey_atom == None)
		XSetClipMask(xfi->display, xfi->gc, None);
	XSync(xfi->display, FALSE);

	XShmDetach(xfi->display, &shminfo);
	XFree(image);
}
Пример #17
0
/**
 * Allocate a shared memory XImage back buffer for the given XMesaBuffer.
 * Return:  GL_TRUE if success, GL_FALSE if error
 */
static GLboolean
alloc_back_shm_ximage(XMesaBuffer b, GLuint width, GLuint height)
{
   /*
    * We have to do a _lot_ of error checking here to be sure we can
    * really use the XSHM extension.  It seems different servers trigger
    * errors at different points if the extension won't work.  Therefore
    * we have to be very careful...
    */
   GC gc;
   int (*old_handler)(XMesaDisplay *, XErrorEvent *);

   if (width == 0 || height == 0) {
      /* this will be true the first time we're called on 'b' */
      return GL_FALSE;
   }

   b->backxrb->ximage = XShmCreateImage(b->xm_visual->display,
                                        b->xm_visual->visinfo->visual,
                                        b->xm_visual->visinfo->depth,
                                        ZPixmap, NULL, &b->shminfo,
                                        width, height);
   if (b->backxrb->ximage == NULL) {
      _mesa_warning(NULL, "alloc_back_buffer: Shared memory error (XShmCreateImage), disabling.\n");
      b->shm = 0;
      return GL_FALSE;
   }

   b->shminfo.shmid = shmget(IPC_PRIVATE, b->backxrb->ximage->bytes_per_line
			     * b->backxrb->ximage->height, IPC_CREAT|0777);
   if (b->shminfo.shmid < 0) {
      _mesa_warning(NULL, "shmget failed while allocating back buffer.\n");
      XDestroyImage(b->backxrb->ximage);
      b->backxrb->ximage = NULL;
      _mesa_warning(NULL, "alloc_back_buffer: Shared memory error (shmget), disabling.\n");
      b->shm = 0;
      return GL_FALSE;
   }

   b->shminfo.shmaddr = b->backxrb->ximage->data
                      = (char*)shmat(b->shminfo.shmid, 0, 0);
   if (b->shminfo.shmaddr == (char *) -1) {
      _mesa_warning(NULL, "shmat() failed while allocating back buffer.\n");
      XDestroyImage(b->backxrb->ximage);
      shmctl(b->shminfo.shmid, IPC_RMID, 0);
      b->backxrb->ximage = NULL;
      _mesa_warning(NULL, "alloc_back_buffer: Shared memory error (shmat), disabling.\n");
      b->shm = 0;
      return GL_FALSE;
   }

   b->shminfo.readOnly = False;
   mesaXErrorFlag = 0;
   old_handler = XSetErrorHandler(mesaHandleXError);
   /* This may trigger the X protocol error we're ready to catch: */
   XShmAttach(b->xm_visual->display, &b->shminfo);
   XSync(b->xm_visual->display, False);

   if (mesaXErrorFlag) {
      /* we are on a remote display, this error is normal, don't print it */
      XFlush(b->xm_visual->display);
      mesaXErrorFlag = 0;
      XDestroyImage(b->backxrb->ximage);
      shmdt(b->shminfo.shmaddr);
      shmctl(b->shminfo.shmid, IPC_RMID, 0);
      b->backxrb->ximage = NULL;
      b->shm = 0;
      (void) XSetErrorHandler(old_handler);
      return GL_FALSE;
   }

   shmctl(b->shminfo.shmid, IPC_RMID, 0); /* nobody else needs it */

   /* Finally, try an XShmPutImage to be really sure the extension works */
   gc = XCreateGC(b->xm_visual->display, b->frontxrb->drawable, 0, NULL);
   XShmPutImage(b->xm_visual->display, b->frontxrb->drawable, gc,
		 b->backxrb->ximage, 0, 0, 0, 0, 1, 1 /*one pixel*/, False);
   XSync(b->xm_visual->display, False);
   XFreeGC(b->xm_visual->display, gc);
   (void) XSetErrorHandler(old_handler);
   if (mesaXErrorFlag) {
      XFlush(b->xm_visual->display);
      mesaXErrorFlag = 0;
      XDestroyImage(b->backxrb->ximage);
      shmdt(b->shminfo.shmaddr);
      shmctl(b->shminfo.shmid, IPC_RMID, 0);
      b->backxrb->ximage = NULL;
      b->shm = 0;
      return GL_FALSE;
   }

   return GL_TRUE;
}
Пример #18
0
int
main (void)
{
  const int flags = IPC_CREAT | 0666;
  int shmid, semid, msqid;
  FILE *fd;
  pthread_t thread;
  struct sockaddr_in sock_addr;
  int sock;
  unsigned short port;
  socklen_t size;
  int status;

  if ((shmid = shmget (3925, 4096, flags | IPC_EXCL)) < 0)
    {
      /* Attempt to delete the existing shared-memory region, then
	 recreate it.  */
      shmctl (shmget (3925, 4096, flags), IPC_RMID, NULL);
      if ((shmid = shmget (3925, 4096, flags | IPC_EXCL)) < 0)
	{
	  printf ("Cannot create shared-memory region.\n");
	  return 1;
	}	  
    }

  semid = semget (7428, 1, flags);
  msqid = msgget (5294, flags);
  fd = fopen ("/dev/null", "r");

  /* Lock the mutex to prevent the new thread from finishing immediately.  */
  pthread_mutex_lock (&mutex);
  pthread_create (&thread, NULL, thread_proc, 0);
 
  sock = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
  if (sock < 0)
    {
      printf ("Cannot create socket.\n");
      return 1;
    }
 
  sock_addr.sin_family = AF_INET;
  sock_addr.sin_port = 0; /* Bind to a free port.  */
  sock_addr.sin_addr.s_addr = htonl (INADDR_ANY);

  status = bind (sock, (struct sockaddr *) &sock_addr, sizeof (sock_addr));
  if (status < 0)
    {
      printf ("Cannot bind socket.\n");
      return 1;
    }

  /* Find the assigned port number of the socket.  */
  size = sizeof (sock_addr);
  status = getsockname (sock, (struct sockaddr *) &sock_addr, &size);
  if (status < 0)
    {
      printf ("Cannot find name of socket.\n");
      return 1;
    }
  port = ntohs (sock_addr.sin_port);

  status = listen (sock, 1);
  if (status < 0)
    {
      printf ("Cannot listen on socket.\n");
      return 1;
    }

  /* Set breakpoint here.  */

  shmctl (shmid, IPC_RMID, NULL);
  semctl (semid, 0, IPC_RMID, NULL);
  msgctl (msqid, IPC_RMID, NULL);
  fclose (fd);
  close (sock);

  pthread_mutex_unlock (&mutex);
  pthread_join (thread, NULL);

  return 0;
}
Пример #19
0
QNativeImage::QNativeImage(int width, int height, QImage::Format format,bool /* isTextBuffer */, QWidget *widget)
    : xshmimg(0), xshmpm(0)
{
    QX11Info info = widget->x11Info();

    int dd = info.depth();
    Visual *vis = (Visual*) info.visual();

    if (!X11->use_mitshm || format != QImage::Format_RGB16 && X11->bppForDepth.value(dd) != 32) {
        image = QImage(width, height, format);
        // follow good coding practice and set xshminfo attributes, though values not used in this case
        xshminfo.readOnly = true;
        xshminfo.shmaddr = 0;
        xshminfo.shmid = 0;
        xshminfo.shmseg = 0;
        return;
    }

    xshmimg = XShmCreateImage(X11->display, vis, dd, ZPixmap, 0, &xshminfo, width, height);
    if (!xshmimg) {
        qWarning("QNativeImage: Unable to create shared XImage.");
        return;
    }

    bool ok;
    xshminfo.shmid = shmget(IPC_PRIVATE, xshmimg->bytes_per_line * xshmimg->height,
                            IPC_CREAT | 0700);
    ok = xshminfo.shmid != -1;
    if (ok) {
        xshmimg->data = (char*)shmat(xshminfo.shmid, 0, 0);
        xshminfo.shmaddr = xshmimg->data;
        ok = (xshminfo.shmaddr != (char*)-1);
        if (ok)
            image = QImage((uchar *)xshmimg->data, width, height, format);
    }
    xshminfo.readOnly = false;
    if (ok) {
        ok = XShmAttach(X11->display, &xshminfo);
        XSync(X11->display, False);
        if (shmctl(xshminfo.shmid, IPC_RMID, 0) == -1)
            qWarning() << "Error while marking the shared memory segment to be destroyed";
    }
    if (!ok) {
        qWarning() << "QNativeImage: Unable to attach to shared memory segment.";
        if (xshmimg->data) {
            free(xshmimg->data);
            xshmimg->data = 0;
        }
        XDestroyImage(xshmimg);
        xshmimg = 0;
        if (xshminfo.shmaddr)
            shmdt(xshminfo.shmaddr);
        if (xshminfo.shmid != -1)
            shmctl(xshminfo.shmid, IPC_RMID, 0);
        return;
    }
    if (X11->use_mitshm_pixmaps) {
        xshmpm = XShmCreatePixmap(X11->display, DefaultRootWindow(X11->display), xshmimg->data,
                                  &xshminfo, width, height, dd);
        if (!xshmpm) {
            qWarning() << "QNativeImage: Unable to create shared Pixmap.";
        }
    }
}
Пример #20
0
int main(int argc, char* argv[]){
	int i, k, m, n, forkID, mshmID, qshmID;
	key_t mkey, qkey;
	char pre[] = "*** MAIN: ";

	printf("Quicksort and Binary Merge with Multiple Processes:\n\n");

	//read k
	if(scanf("%d", &k) <= 0) perror("Error reading input");
	
	//create struct
	struct qstruct {
		int n;
		int array[k];
	};

	struct qstruct qsort;
	qsort.n = k;

	int a[k];
	//read a
	for(i = 0; i < k; i++){
		if(scanf("%d", &qsort.array[i]) <= 0) perror("Error reading input");
	}
	//read m
	if(scanf("%d", &m) <= 0) perror("Error reading input");
	
	int x[m];
	//read x
	for(i = 0; i < m; i++){
		if(scanf("%d", &x[i]) <= 0) perror("Error reading input");
	}

	//read n
	if(scanf("%d", &n) <= 0) perror("Error reading input");
	
	
	int y[n];
	//read y
	for(i = 0; i < n; i++){
		if(scanf("%d", &y[i]) <= 0) perror("Error reading input");
	}

	//create struct
	struct mstruct {
		int xsize;
		int ysize;
		int x[m];
		int y[n];
		int ret[m + n];
	};



	//create key
	qkey = ftok("./", 'q');

	//create shared memory for qsort
	printf("%sshared memory key = %d\n", pre, qkey);

	if((qshmID = shmget(qkey, sizeof(struct qstruct), IPC_CREAT | 0666)) < 0){
		printf("Failed to create shared memory.\n");
		exit(1);
	}	
	printf("%sshared memory created\n", pre);

	//set shared memory values
	struct qstruct* qdata;
	qdata = (struct qstruct*) shmat(qshmID, NULL, 0);
	qdata->n = qsort.n;
	for(i = 0; i < qsort.n; i++){
		qdata->array[i] = qsort.array[i];
	}
	
	printf("%sshared memeory attached and is ready to use\n\n", pre);



	//create key
	mkey = ftok("./", 'm');

	//create shared memory for merge
	printf("%sshared memory key = %d\n", pre, mkey);

	if((mshmID = shmget(mkey, sizeof(struct mstruct), IPC_CREAT | 0666)) < 0){
		printf("Failed to create shared memory.\n");
		exit(1);
	}	
	printf("%sshared memory created\n", pre);

	//set shared memory values
	struct mstruct* mdata;
	mdata = (struct mstruct*) shmat(mshmID, NULL, 0);
	/*if((int) qdata < 0){
		printf("Failed to attached shared memory.");
		exit(1);
	}*/
	
	printf("%sshared memeory attached and is ready to use\n\n", pre);

	//set shared memory to stored values
	mdata->xsize = m;
	mdata->ysize = n;

	for(i = 0; i < m || i < n; i++){
		if(i < m) mdata->x[i] = x[i];
		if(i < n) mdata->y[i] = y[i];
	}
	

	//print out input
	printf("Input array for qsort has %d elements:\n", k);
	printf("  ");
	for(i = 0; i < k; i++) printf("  %d",qsort.array[i]);
	printf("\n");
	
	printf("Input array x[] for merge has %d elements:\n", m);
	printf("  ");
	for(i = 0; i < m; i++) printf("  %d", mdata->x[i]);
	printf("\n");
	
	printf("Input array y[] for merge has %d elements:\n", n);
	printf("  ");
	for(i = 0; i < n; i++) printf("  %d", mdata->y[i]);
	printf("\n");



	//generate argv for child
	char* args[5];
	char right[16]; sprintf(right, "%d", k - 1);
	char asize[16]; sprintf(asize, "%d", k);
	char qprog[] = {"qsort"}; char left[] = {"0"};
	args[0] = qprog; args[1] = left; args[2] = right; args[3] = asize; args[4] = NULL;
	
	printf("%sabout to spawn the process for qsort\n", pre);

	//fork and execute
	forkID = fork();
	if(forkID == 0){
		if(execvp("./qsort", args) < 0){
			printf("execvp() failed\n");
			exit(1);
		}
		exit(0);
	}


	//generate argv for child
	char mprog[] = {"merge"}; 
	char xsize[16]; sprintf(xsize, "%d", m);
	char ysize[16]; sprintf(ysize, "%d", n);
	args[0] = mprog; args[1] = xsize; args[2] = ysize; args[3] = NULL;
 
	printf("%sabout to spawn the process for merge\n", pre);
	
	//fork and execute
	forkID = fork();
	if(forkID == 0){
		if(execvp("./merge", args) < 0){
			printf("execvp() failed\n");
			exit(1);
		}
		exit(0);
	}

	//wait for both children to complete
	wait();
	wait();

	//print out sorted arrays
	printf("\n%ssorted array by qsort:\n  ", pre);
	for(i = 0; i < k; i++) printf("  %d", qdata->array[i]);
	printf("\n");

	printf("%smerged array:\n  ", pre);
	for(i = 0; i < m + n; i++) printf("  %d", mdata->ret[i]);
	printf("\n");


	//detach and remove shared memory
	shmdt((void *) qdata);
	printf("\n%sshared memory successfully detached\n", pre);
	shmctl(qshmID, IPC_RMID, NULL);
	printf("%sshared memory successfully removed\n\n", pre);

	shmdt((void *) mdata);
	printf("%sshared memory successfully detached\n", pre);
	shmctl(mshmID, IPC_RMID, NULL);
	printf("%sshared memory successfully removed\n\n", pre);



}
Пример #21
0
AstraDriver::AstraDriver(ros::NodeHandle& n, ros::NodeHandle& pnh) :
    nh_(n),
    pnh_(pnh),
    device_manager_(AstraDeviceManager::getSingelton()),
    config_init_(false),
    data_skip_ir_counter_(0),
    data_skip_color_counter_(0),
    data_skip_depth_counter_ (0),
    ir_subscribers_(false),
    color_subscribers_(false),
    depth_subscribers_(false),
    depth_raw_subscribers_(false)
{

  genVideoModeTableMap();

  readConfigFromParameterServer();

#if MULTI_ASTRA
	int bootOrder, devnums;
	pnh.getParam("bootorder", bootOrder);
	pnh.getParam("devnums", devnums);
	if( devnums>1 )
	{
		int shmid;
		char *shm = NULL;
		char *tmp;
		if(  bootOrder==1 )
		{
			if( (shmid = shmget((key_t)0401, 1, 0666|IPC_CREAT)) == -1 )   
			{ 
				ROS_ERROR("Create Share Memory Error:%s", strerror(errno));
			}
			shm = (char *)shmat(shmid, 0, 0);  
			*shm = 1;
			initDevice();
			ROS_WARN("*********** device_id %s already open device************************ ", device_id_.c_str());
			*shm = 2;
		}
		else 	
		{	
			if( (shmid = shmget((key_t)0401, 1, 0666|IPC_CREAT)) == -1 )   
			{ 
			  	ROS_ERROR("Create Share Memory Error:%s", strerror(errno));
			}
			shm = (char *)shmat(shmid, 0, 0);
			while( *shm!=bootOrder);
			 initDevice();
			 ROS_WARN("*********** device_id %s already open device************************ ", device_id_.c_str());
			*shm = (bootOrder+1);
		}
		if(  bootOrder==1 )
		{
			while( *shm!=(devnums+1)) ;
			if(shmdt(shm) == -1)  
			{  
				ROS_ERROR("shmdt failed\n");  
			} 
			if(shmctl(shmid, IPC_RMID, 0) == -1)  
			{  
				ROS_ERROR("shmctl(IPC_RMID) failed\n");  
			}
		 }
		 else
		 {
		 	if(shmdt(shm) == -1)  
			{  
				ROS_ERROR("shmdt failed\n");  
			} 
		 }
	 }
	 else
	 {
	 	initDevice();
	 }
#else
  initDevice();

#endif
  // Initialize dynamic reconfigure
  reconfigure_server_.reset(new ReconfigureServer(pnh_));
  reconfigure_server_->setCallback(boost::bind(&AstraDriver::configCb, this, _1, _2));

  while (!config_init_)
  {
    ROS_DEBUG("Waiting for dynamic reconfigure configuration.");
    boost::this_thread::sleep(boost::posix_time::milliseconds(100));
  }
  ROS_DEBUG("Dynamic reconfigure configuration received.");

  advertiseROSTopics();

}
Пример #22
0
int main( int pArgc, const char** pArgs )
{
   const char* lQueryPtr;
   int         lLock;
   int         lMemId;
   char        lQuery[4096];
   char        lOp[12];
   BOOL        lPrintTitle;


   #ifndef _NO_IPC_
      union semun lNULL;
   #endif

   #ifdef _NO_IPC_
 
      gGlobalState.Clear();
      if( InitLogFile() )
      {
         fprintf( gLogFile, "IMR Init version 0.13.13b %s\n", GetTime( time(NULL)) );
      }

   #endif


   #ifdef _FAST_CGI_
   while( FCGI_Accept() >= 0 )
   {
   #endif
      lPrintTitle = TRUE;

      /* Send the header required by the server */
      printf("Content-type: text/plain%c%c", 10, 10);


      lQueryPtr = getenv( "QUERY_STRING" );

      if( lQueryPtr == NULL )
      {
         printf( "No parameters\n" );
      }
      else
      {

         StrMaxCopy( lQuery, lQueryPtr, 4096 );

         UnpadQuery( lQuery );

         if( sscanf( lQuery, "=%11s", lOp ) == 1 )
         {
            #ifndef _FAST_CGI_
               /* Change the local directory */
               char* lPathEnd = strrchr( pArgs[0], '/' );

               if( lPathEnd != NULL )
               {
                  *lPathEnd = 0;
                  chdir( pArgs[0] );
               }
            #endif


            if( !strcmp( lOp, "RESET" ) )
            {
               printf( "RESET OK\n\n" );

               #ifdef _NO_IPC_
                  /*
                  // gGlobalState.Clear();
                  // sleep( 2 );
                  // return 0;
                  // break;
                  */
               #else

                  lLock  = semget( IR_SEM_KEY, 1, 0777 );
                  lMemId = shmget( IR_SHMEM_KEY, sizeof( IRState ), 0666 );

                  if( lLock != -1 )
                  {
                     semctl( lLock, 0, IPC_RMID, lNULL );
                  }

                  if( lMemId != -1 )
                  {
                     shmctl( lMemId, IPC_RMID, NULL );
                  }

               #endif

               if( InitLogFile() )
               {
                  fprintf( gLogFile, "IMR Reset %s\n", GetTime( time(NULL)) );
               }

               #ifdef _FAST_CGI_
                  break;
               #endif

            }
            else if( !strcmp( lOp, "SET_MESSAGE" ) )
            {
            }
            /*
            else if( !strcmp( lOp, "STICK" ) )
            {
               // Fork and leave a child running for 1 hour

               int lCode = fork();
               if( lCode == 0 )
               {
                  if( InitLogFile() )
                  {
                     fprintf( gLogFile, "STICK Start %s\n", GetTime( time(NULL)) );
                     CloseLogFile();
                  }

                  close( 0 );
                  close( 1 );
                  close( 2 );
                  sleep( 3600 );

                  if( InitLogFile() )
                  {
                     fprintf( gLogFile, "STICK End %s\n", GetTime( time(NULL)) );
                     CloseLogFile();
                  }

               }
               
               else if( lCode == -1 )
               {
                  printf( "ERROR\n" );
               }
               else
               {
                  printf( "SUCCESS\n" );
               }
               
            }
            */
            else
            {
               IRState* lState = NULL;

               #ifdef _NO_IPC_
                  lState = &gGlobalState;

               #else

                  int      lLock;        /* Semaphore */
                  int      lMemId;       /* Shared memory */

                  struct sembuf lSemOp;

                  lSemOp.sem_flg = 0;  /*Avoid corruption but must not core-dump SEM_UNDO;  // Risky but prevents dead-lock */
                  lSemOp.sem_num  = 0;

                  /* First try to create the structure for the first time */
                  /* Lock the data struct */
                  lLock = semget( IR_SEM_KEY, 1, 0777|IPC_CREAT|IPC_EXCL );

                  if( lLock != -1 )
                  {
                     union semun lArg;
               
                     /* Initialize the newly created semaphore */
                     lArg.val = 1;
 
                     semctl( lLock, 0, SETVAL, lArg );
                  }
                  else
                  {
                     lLock = semget( IR_SEM_KEY, 1, 0777 );
                  }

                  if( lLock == -1 )
                  {
                     printf( "Unable to get semaphore\n" );
                  }
                  else
                  {
                     lSemOp.sem_op   = -1;

                     if( semop( lLock, &lSemOp, 1 ) == -1 )
                     {
                        printf( "Unable to decrement semaphore\n" );
                        lLock = -1;
                     }
                     else
                     {

                        /* From here we can work safely */

                        lMemId = shmget( IR_SHMEM_KEY, sizeof( IRState ), 0666|IPC_CREAT|IPC_EXCL );

                        if( lMemId != -1 )
                        {
                           lState = (IRState*)shmat( lMemId, NULL, 0 );

                           if( (int)lState == -1 )
                           {
                              lState = NULL;
                           }

                           if( lState == NULL )
                           {
                              printf( "Unable to attach shmem\n" );
                           }
                           else
                           {
                              Clear( lState );

                              if( InitLogFile() )
                              {
                                 fprintf( gLogFile, "IMR Init %s\n", GetTime( time(NULL)) );
                              }

                           }
                        }
                        else
                        {
                           lMemId = shmget( IR_SHMEM_KEY, sizeof( IRState ), 0666 );

                           if( lMemId == -1 )
                           {
                              printf( "Unable to get shmem\n" );
                           }
                           else
                           {
                              lState = (IRState*)shmat( lMemId, NULL, 0 );

                              if( (int)lState == -1 )
                              {
                                 lState = NULL;
                              }

                              if( lState == NULL )
                              {
                                 printf( "Unable to attach shmem\n" );
                              }
                           }
                        }
                     }
                  }

               #endif
   
               if( lState != NULL )
               {

                  lPrintTitle = FALSE;

                  VerifyExpirations( lState );

                  if( !strcmp( lOp, "REFRESH" ) )
                  {
                     int lUserIndex;
                     int lUserId;
                     int lTimeStamp;

                     if( sscanf( lQuery, "%*s %d-%u %d", &lUserIndex, &lUserId, &lTimeStamp )==3 )
                     {
                        PrintStateChange( lState, lUserIndex, lUserId, lTimeStamp );
                     }
                  }
                  else if( !strcmp( lOp, "ADD_CHAT" ) )
                  {
                     int  lUserIndex;
                     int  lUserId;
                     char lChatMessage[200];

                     if( sscanf( lQuery, "%*s %d-%u %200s", &lUserIndex, &lUserId, lChatMessage )==3 )
                     {
                        Unpad( lChatMessage );
                        AddChatMessage( lState, lUserIndex, lUserId, lChatMessage );
                     }
                  }
                  /*   URL?=ADD_USER MAJOR-MINORID VERSION KEY2 KEY3 ALIAS */
                  else if( !strcmp( lOp, "ADD_USER" ) )
                  {
                     int lMajorID;
                     int lMinorID;
                     int  lVersion;
                     unsigned int lKey2;
                     unsigned int lKey3;
                     char lUserName[40];

                     #ifdef _EXPIRED_ 
                        AddUser(  lState, "User", 1,-1, -1, 0, 0  );
                     #else
                        if( sscanf( lQuery, "%*s %d-%d %d %d %d %40s", &lMajorID, &lMinorID, &lVersion, &lKey2, &lKey3, lUserName )==6 )
                        {
                           Unpad( lUserName );
                           AddUser( lState, lUserName, lVersion,lMajorID, lMinorID, lKey2, lKey3  );
                        }
                     #endif
                  }
                  /* URL?=ADD_GAME USER_ID GAME_NAME TRACK_NAME NBLAP WEAPON PORT */
                  else if( !strcmp( lOp, "ADD_GAME" ) )
                  {
                     int       lUserIndex;
                     int       lUserId;
                     int       lNbLap;
                     char      lGameName[40];
                     char      lTrackName[40];
                     int       lWeapon;
                     unsigned  lPort;
               
                     if( sscanf( lQuery, "%*s %d-%u %40s %40s %d %d %u", &lUserIndex, &lUserId, lGameName, lTrackName, &lNbLap, &lWeapon, &lPort )==7 )
                     {
                        const char* lRemoteAddr = getenv( "REMOTE_ADDR" );

                        if( (lRemoteAddr != NULL)&&(strlen(lRemoteAddr) != 0) )
                        {
                           Unpad( lTrackName );
                           Unpad( lGameName );
                           AddGame( lState, lGameName, lTrackName, lNbLap, lUserIndex, lUserId, lRemoteAddr, lPort, lWeapon  );
                        }
                     }
                  }
                  else if( !strcmp( lOp, "JOIN_GAME" ) )
                  {
                     int   lUserIndex;
                     int   lUserId;
                     int   lGameIndex;
                     int   lGameId;
               
                     if( sscanf( lQuery, "%*s %d-%u %d-%u", &lGameIndex, &lGameId, &lUserIndex, &lUserId )==4 )
                     {
                        JoinGame( lState, lGameIndex, lGameId, lUserIndex, lUserId );
                     }
                  }
                  else if( !strcmp( lOp, "DEL_GAME" ) )
                  {
                     int   lUserIndex;
                     int   lUserId;
                     int   lGameIndex;
                     int   lGameId;
               
                     if( sscanf( lQuery, "%*s %d-%u %d-%u", &lGameIndex, &lGameId, &lUserIndex, &lUserId )==4 )
                     {
                        DeleteGame( lState, lGameIndex, lGameId, lUserIndex, lUserId );
                     }
                  }
                  else if( !strcmp( lOp, "LEAVE_GAME" ) )
                  {
                     int   lUserIndex;
                     int   lUserId;
                     int   lGameIndex;
                     int   lGameId;
               
                     if( sscanf( lQuery, "%*s %d-%u %d-%u", &lGameIndex, &lGameId, &lUserIndex, &lUserId )==4 )
                     {
                        LeaveGame( lState, lGameIndex, lGameId, lUserIndex, lUserId );
                     }
                  }
                  else if( !strcmp( lOp, "DEL_USER" ) )
                  {
                     int   lUserIndex;
                     int   lUserId;
               
                     if( sscanf( lQuery, "%*s %d-%u", &lUserIndex, &lUserId )==2 )
                     {
                        DeleteUser( lState, lUserIndex, lUserId );
                     }
                  }
                  else if( !strcmp( lOp, "START_GAME" ) )
                  {
                     int   lUserIndex;
                     int   lUserId;
                     int   lGameIndex;
                     int   lGameId;
               
                     if( sscanf( lQuery, "%*s %d-%u %d-%u", &lGameIndex, &lGameId, &lUserIndex, &lUserId )==4 )
                     {
                        StartGame( lState, lGameIndex, lGameId, lUserIndex, lUserId );
                     }
                  }
                  else
                  {
                     lPrintTitle = TRUE;
                  }
               }

               #ifdef _NO_IPC_
                  lState = NULL;
               #else
                  /* Release lock */
                  if( lLock != -1 )
                  {
                     lSemOp.sem_op   = 1;

                     semop( lLock, &lSemOp, 1 );

                     /* Release memory */
                     if( lState != NULL )
                     {
                        shmdt( (char*)lState );
                     }
                  }
                  
               #endif
               
            }
         }
      }

      CloseLogFile();

      if( lPrintTitle )
      {
         printf( "Internet Meeting Room (c)1996,97 GrokkSoft inc.\n" );
      }
  #ifdef _FAST_CGI_
  }
  #endif

   return 0;
}
Пример #23
0
/*  **************************************************************************************************************
 *	Test shmat, shmctl, shmdt, shmget system calls.
 *  **************************************************************************************************************
 */
int shm_tests( void * the_argp )
{	
#if !TARGET_OS_EMBEDDED
	int					my_err;
	int					my_shm_id;
	void *				my_shm_addr = NULL;
	struct shmid_ds		my_shmid_ds;

	my_shm_id = shmget( IPC_PRIVATE, 4096, (IPC_CREAT | IPC_R | IPC_W) );
	if ( my_shm_id == -1 ) {
		printf( "shmget failed with error %d - \"%s\" \n", errno, strerror( errno) );
		goto test_failed_exit;
	}

	my_shm_addr = shmat( my_shm_id, NULL, SHM_RND );
	if ( my_shm_addr == (void *) -1 ) {
		my_shm_addr = NULL;
		printf( "shmat failed with error %d - \"%s\" \n", errno, strerror( errno) );
		goto test_failed_exit;
	}

	/* try writing to the shared segment */
	*((char *) my_shm_addr) = 'A';

	my_err = shmctl( my_shm_id, IPC_STAT, &my_shmid_ds );
	if ( my_err == -1 ) {
		printf( "shmctl failed with error %d - \"%s\" \n", errno, strerror( errno) );
		goto test_failed_exit;
	}
	if ( my_shmid_ds.shm_segsz != 4096 ) {
		printf( "shmctl failed get correct shared segment size \n" );
		goto test_failed_exit;
	}
	if ( getpid( ) != my_shmid_ds.shm_cpid ) {
		printf( "shmctl failed get correct creator pid \n" );
		goto test_failed_exit;
	}

	my_err = shmdt( my_shm_addr );
	if ( my_err == -1 ) {
		printf( "shmdt failed with error %d - \"%s\" \n", errno, strerror( errno) );
		goto test_failed_exit;
	}
	
	my_err = shmctl( my_shm_id, IPC_RMID, NULL );
	if ( my_err == -1 ) {
		printf("shmctl failed to delete memory segment.\n");
		goto test_failed_exit;
	}
	
	my_shm_addr = NULL;
	 
	my_err = 0;
	goto test_passed_exit;

test_failed_exit:
	my_err = -1;
	
test_passed_exit:
	if ( my_shm_addr != NULL ) {
		shmdt( my_shm_addr );
		shmctl( my_shm_id, IPC_RMID, NULL);
	}
	return( my_err );
#else
	printf( "\t--> Not supported on EMBEDDED TARGET\n" );
	return 0;
#endif
}
Пример #24
0
LedDeviceMemory::~LedDeviceMemory()
{
	// delete memory
	shmctl(_shID, IPC_RMID, 0);
	std::cout << "Successfully detached and deleted shared memory" << std::endl;
}
Пример #25
0
DFBResult
dfb_x11_image_init_handler( DFBX11 *x11, x11Image *image )
{
     Visual *visual;
     XImage *ximage;

     D_MAGIC_ASSERT( image, x11Image );

     if (!x11->use_shm)
          return DFB_UNSUPPORTED;

     /* Lookup visual. */
     visual = x11->visuals[DFB_PIXELFORMAT_INDEX(image->format)];
     if (!visual)
          return DFB_UNSUPPORTED;

     image->visual = visual;

     XLockDisplay( x11->display );

     ximage = XShmCreateImage( x11->display, image->visual, image->depth,
                               ZPixmap, NULL, &image->seginfo, image->width, image->height );
     if (!ximage) {
          D_ERROR( "X11/ShmImage: Error creating shared image (XShmCreateImage)!\n");
          XUnlockDisplay( x11->display );
          return DFB_FAILURE;
     }

     /* we firstly create our shared memory segment with the size we need, and
      correct permissions for the owner, the group and the world --> 0777 */
     image->seginfo.shmid = shmget( IPC_PRIVATE, 
                                    ximage->bytes_per_line * ximage->height,
                                    IPC_CREAT | 0777 );
     if (image->seginfo.shmid < 0)
          goto error;

     /* Then, we have to attach the segment to our process, and we let the
        function search the correct memory place --> NULL. It's safest ! */
     image->seginfo.shmaddr = shmat( image->seginfo.shmid, NULL, 0 );
     if (!image->seginfo.shmaddr)
          goto error_shmat;

     ximage->data = image->seginfo.shmaddr;

     /* We set the buffer in Read and Write mode */
     image->seginfo.readOnly = False;

     if (!XShmAttach( x11->display, &image->seginfo ))
          goto error_xshmattach;

     image->ximage = ximage;
     image->pitch  = ximage->bytes_per_line;

     image->pixmap = XShmCreatePixmap( x11->display, DefaultRootWindow(x11->display), ximage->data,
                                       &image->seginfo, image->width, image->height, image->depth );

     image->gc = XCreateGC( x11->display, image->pixmap, 0, NULL );

     XUnlockDisplay( x11->display );

     return DFB_OK;


error_xshmattach:
     shmdt( image->seginfo.shmaddr );

error_shmat:
     shmctl( image->seginfo.shmid, IPC_RMID, NULL );

error:
     XDestroyImage( ximage );

     XUnlockDisplay( x11->display );

     return DFB_FAILURE;
}
Пример #26
0
int main (int argc, char *argv[])
{
	// Sema for tansmit the type
	key_t sem_type_key = ftok(PATH, TYPE);
	int sem_type = semget(sem_type_key, 1, IPC_CREAT | PERMS);
	semReset(sem_type, 0);

	key_t sem_control_key = ftok(PATH, CONTROL);
	int sem_control = semget(sem_control_key, 2, IPC_CREAT | PERMS);
	semReset(sem_control, 0);
	semReset(sem_control, 1);	
	
	// Sema for control Shared Mem Stock
	key_t sem_DispSrv_key = ftok(PATH, STOCK);
	int sem_DispSrv = semget(sem_DispSrv_key, 1, IPC_CREAT | PERMS);
	semReset(sem_DispSrv, 0);

	// Shared mem between monitor and server
	key_t shm_DispSrv_key = ftok(PATH, STOCKSHM);
	int shm_DispSrv = shmget(shm_DispSrv_key, sizeof(TSharedStock), IPC_CREAT | PERMS); // Creation com display server shm

	// File Parameters
	/* Time Function for filename definition */
	time_t now = time(NULL);
	struct tm *time = localtime(&now);
	char date_time[30];
	strftime(date_time,sizeof(date_time),"%d%m%y_%H%M%S", time);

	pid_t process_id = fork(); // Premier Fork (Server, Afficheur)
	if (process_id < 0) {
		perror("Error while attempting Fork (Server/Afficheur de Resultat)");
		exit(19);
	}

	//Afficheur (Parent)//
	else if (process_id > 0){
		int level = 0;
		showMainMenu(level, date_time);
	} 
	/*Tampon Serveur (Child)*/
	else{
		// DAEMON CODE START //
		//daemonize();
		// PROCESS NOW A DAEMON //
		//***********//
		//*SEMA INIT*//
		//***********//
		// Sema for control shared mem race
		key_t sem_mutex_key = ftok(PATH, MUTEX);
		int sem_mutex = semget(sem_mutex_key, 1, IPC_CREAT | PERMS);
		semReset(sem_mutex, 0);

		key_t sem_race_key = ftok(PATH, RACE);
	    int sem_race = semget(sem_race_key, 22, IPC_CREAT | PERMS);
	    int r;
	    for(r = 0; r < 22; r++) semReset(sem_race, r);				
		//*****************//
		//*SHARED MEM INIT*//
		//*****************//
		key_t shm_race_key = ftok(PATH, RACESHM);
		int shm_race = shmget(shm_race_key, 22*sizeof(TTabCar), IPC_CREAT | PERMS);

		//***********//
		//*FORK INIT*//
		//***********//
		process_id = fork(); // Deuxieme Fork (Server, Pilot)
		if (process_id < 0) {
			perror("Error while attempting Fork (Server/Pilot)");
			exit(19);
		}
		//Pilots (Child)//
		else if (process_id == 0) forkPilots(); // Pilot forking function
		//Server (Parent)
		else server(date_time); // Main server function

		for(r = 0; r < 22; r++){
			if(semGet(sem_race, r) != 1) semReset(sem_race, r);
		 	semctl(sem_race, r, IPC_RMID, NULL);

		 }
		if(semGet(sem_mutex, 0) != 1) semReset(sem_mutex, 0);
		semctl(sem_mutex, 0, IPC_RMID, NULL);
		if(semGet(sem_type, 0) != 1) semReset(sem_type, 0);
		semctl(sem_type, 0, IPC_RMID, NULL);
		if(semGet(sem_control, 0) != 1) semReset(sem_control, 0);
		if(semGet(sem_control, 1) != 1) semReset(sem_control, 1);
		semctl(sem_control, 0, IPC_RMID, NULL);
		semctl(sem_control, 1, IPC_RMID, NULL);
		shmctl(shm_race, IPC_RMID, NULL);
		shmctl(shm_DispSrv, IPC_RMID, NULL);
		if(semGet(sem_DispSrv, 0) != 1) semReset(sem_DispSrv, 0);
		semctl(sem_DispSrv, 0, IPC_RMID, NULL);
	}
	return EXIT_SUCCESS;
}
Пример #27
0
int ipcrm_main(int argc, char **argv)
{
	int c;
	int error = 0;

	/* if the command is executed without parameters, do nothing */
	if (argc == 1)
		return 0;
#if IPCRM_LEGACY
	/* check to see if the command is being invoked in the old way if so
	   then run the old code. Valid commands are msg, shm, sem. */
	{
		type_id what = 0; /* silence gcc */
		char w;

		w=argv[1][0];
		if ( ((w == 'm' && argv[1][1] == 's' && argv[1][2] == 'g')
		       || (argv[1][0] == 's'
		           && ((w=argv[1][1]) == 'h' || w == 'e')
		           && argv[1][2] == 'm')
		     ) && argv[1][3] == '\0'
		) {

			if (argc < 3)
				bb_show_usage();

			if (w == 'h')
				what = SHM;
			else if (w == 'm')
				what = MSG;
			else if (w == 'e')
				what = SEM;

			if (remove_ids(what, argc-2, &argv[2]))
				fflush_stdout_and_exit(EXIT_FAILURE);
			printf("resource(s) deleted\n");
			return 0;
		}
	}
#endif /* IPCRM_LEGACY */

	/* process new syntax to conform with SYSV ipcrm */
	while ((c = getopt(argc, argv, "q:m:s:Q:M:S:h?")) != -1) {
		int result;
		int id = 0;
		int iskey = (isupper)(c);

		/* needed to delete semaphores */
		union semun arg;

		arg.val = 0;

		if ((c == '?') || (c == 'h')) {
			bb_show_usage();
		}

		/* we don't need case information any more */
		c = tolower(c);

		/* make sure the option is in range: allowed are q, m, s */
		if (c != 'q' && c != 'm' && c != 's') {
			bb_show_usage();
		}

		if (iskey) {
			/* keys are in hex or decimal */
			key_t key = xstrtoul(optarg, 0);

			if (key == IPC_PRIVATE) {
				error++;
				bb_error_msg("illegal key (%s)", optarg);
				continue;
			}

			/* convert key to id */
			id = ((c == 'q') ? msgget(key, 0) :
				  (c == 'm') ? shmget(key, 0, 0) : semget(key, 0, 0));

			if (id < 0) {
				const char *errmsg;

				error++;
				switch (errno) {
				case EACCES:
					errmsg = "permission denied for";
					break;
				case EIDRM:
					errmsg = "already removed";
					break;
				case ENOENT:
					errmsg = "invalid";
					break;
				default:
					errmsg = "unknown error in";
					break;
				}
				bb_error_msg("%s %s (%s)", errmsg, "key", optarg);
				continue;
			}
		} else {
			/* ids are in decimal */
			id = xatoul(optarg);
		}

		result = ((c == 'q') ? msgctl(id, IPC_RMID, NULL) :
				  (c == 'm') ? shmctl(id, IPC_RMID, NULL) :
				  semctl(id, 0, IPC_RMID, arg));

		if (result) {
			const char *errmsg;
			const char *const what = iskey ? "key" : "id";

			error++;
			switch (errno) {
			case EACCES:
			case EPERM:
				errmsg = "permission denied for";
				break;
			case EINVAL:
				errmsg = "invalid";
				break;
			case EIDRM:
				errmsg = "already removed";
				break;
			default:
				errmsg = "unknown error in";
				break;
			}
			bb_error_msg("%s %s (%s)", errmsg, what, optarg);
			continue;
		}
	}

	/* print usage if we still have some arguments left over */
	if (optind != argc) {
		bb_show_usage();
	}

	/* exit value reflects the number of errors encountered */
	return error;
}
Пример #28
0
void sharedMemory::remove() {
   shmctl(shmid, IPC_RMID, 0);
   printf("Shared memory segment marked for deletion\n");

   return;
}
Пример #29
0
void* server_thread (void* t)
{
/* shared memory segment id           */
int MyKey;
int reqMemSegID;             
int resMemSegID;
/* shared memory flags                */
int shmFlags;               
    
/*pointer to the queue			*/
struct queue *request_ring;
struct queue *response_ring;


/*Keys to request & response structures*/
int REQ_KEY,RES_KEY;     

/*Get the Thread ID */
int tid =  (int)(int*)t;
MyKey   =  (int)message_box->client[tid];  
printf("Servicing Client with Process ID %d, Thread ID %d\n",(int)MyKey,tid);

/*Get the keys for both rings*/
REQ_KEY = ftok(".", (int) MyKey * 0xAA );    
RES_KEY = ftok(".", (int) MyKey * 0x33 );

/*Should not happen*/
assert(REQ_KEY != RES_KEY);

#if 1
/*---------------------------------------*/
/* Create shared memory segment          */
/* Give everyone read/write permissions. */
/*---------------------------------------*/

shmFlags = IPC_CREAT | SHM_PERM;
/*Request ring creation*/
 if ( (reqMemSegID = 
  shmget(REQ_KEY, SHM_SIZE, shmFlags)) < 0 )
   {
       perror("SERVER: shmget");
       exit(EXIT_FAILURE);
   }
printf("Created shared location for request ring buffer\n");
/*Response ring creation*/
if ( (resMemSegID = 
  shmget(RES_KEY, SHM_SIZE, shmFlags)) < 0 )
   {
       perror("SERVER: shmget");
       exit(EXIT_FAILURE);
   }
printf("Created shared location for response ring buffer\n");

/*-------------------------------------------*/
/* Attach the segment to the process's data  */
/* space at an address                       */
/* selected by the system.                   */
/*-------------------------------------------*/
/*Changed by Pradeep*/
shmFlags = 0;
/*Get Request Ring*/
if ( (request_ring = 
      shmat(reqMemSegID, NULL, shmFlags)) == 
  (void *) -1 )
   {
       perror("SERVER: shmat");
       exit(EXIT_FAILURE);
   }
printf("Request Ring buffer attached to process\n");
/*Get Response Ring*/
if ( (response_ring = 
      shmat(resMemSegID, NULL, shmFlags)) == 
  (void *) -1 )
   {
       perror("SERVER: shmat");
       exit(EXIT_FAILURE);
   }
printf("Response Ring buffer attached to process\n");


while(1){
	if(is_empty(request_ring))
	{
		//pthread_cond_wait(&cond_thread, &mutex_thread);
		sleep(1);
	}
	else if(!is_empty(request_ring))
	{	
		printf("Got a request, Dequeuing it \n");	
		Task temp = dequeue(request_ring);
		compute_mod(&temp);
		printf("Computed Mod\n");
		
	        enqueue(response_ring,temp);
	}
}
/*------------------------------------------------*/
/* Call shmdt() to detach shared memory segment.  */
/*------------------------------------------------*/
   if ( shmdt(request_ring) < 0 )
   {
       perror("SERVER: shmdt");
       exit(EXIT_FAILURE);
   }

  if ( shmdt(response_ring) < 0 )
   {
       perror("SERVER: shmdt");
       exit(EXIT_FAILURE);
   }

    

/*--------------------------------------------------*/
/* Call shmctl to remove shared memory segment.     */
/*--------------------------------------------------*/
   if (shmctl(reqMemSegID, IPC_RMID, NULL) < 0)
   {
       perror("SERVER: shmctl");
       exit(EXIT_FAILURE);
   }

  if (shmctl(resMemSegID, IPC_RMID, NULL) < 0)
   {
       perror("SERVER: shmctl");
       exit(EXIT_FAILURE);
   }
 

   exit(EXIT_SUCCESS);
#endif
}  /* end of main() */
Пример #30
0
main()
{//PROCESO///////////////////////////////////////////////////////////////////////
	
	
	int key_proceso = ftok(FILEKEY, KEY_PROCESO);
	if (key_proceso == -1) {
		fprintf (stderr, "Error con la key \n");
		return -1; 
	}    
	int id_zone0 = shmget (key_proceso, sizeof(flags)*MAXBUF_PROCESO, 0777 | IPC_CREAT);
	if (id_zone0 == -1) {
		fprintf (stderr, "Error con id_zone 1 \n");
		return -1; 
	} 
	flags = shmat(id_zone0, (char *)0, 0);	
	if (flags == NULL) {
		fprintf (stderr, "Error reservando memoria flags\n");
		return -1; 
	}
	
////////////////////////////////////////////////////////////////////////////
	
  
  
 //turno///////////////////////////////////////////////////////////////////////
	
	
	int key_turno = ftok(FILEKEY, KEY_TURNO);
	if (key_turno == -1) {
		fprintf (stderr, "Error con la key \n");
		return -1; 
	}    
	int id_zone1 = shmget (key_turno, sizeof(turno)*MAXBUF_PROCESO, 0777 | IPC_CREAT);
	if (id_zone1 == -1) {
		fprintf (stderr, "Error con id_zone 1 \n");
		return -1; 
	} 
	turno = shmat(id_zone1,NULL , 0);	
	if (turno == NULL) {
		fprintf (stderr, "Error reservando memoria en turno\n");
		return -1; 
	}
	
//////////////////////////////////////////////////////////////////////////// 
 //interesado///////////////////////////////////////////////////////////////////////
	/* Key to shared memory */
	int key_contador = ftok(FILEKEY, KEY_CONTADOR);
	if (key_contador == -1) {
		fprintf (stderr, "Error con la key \n");
		return -1; 
	}    
	
	/*Creacion de memoria compartida */
	int id_zone3 = shmget (key_contador, sizeof(int)*2, 0777 | IPC_CREAT);
	if (id_zone3 == -1) {
		fprintf (stderr, "Error con id_zone \n");
		return -1; 
	} 
		
	/* we declared to zone to share */
	interesado = (int *)shmat (id_zone3, (char *)0, 0);
	if (interesado == NULL) {
		fprintf (stderr, "Error reservando memoria interesado\n");
		return -1; 
	}
////////////////////////////////////////////////////////////////////////////


 
 char c;
 int shmid;
 key_t key;
 
 
 /*Lo llama con es ID */
 key = 5678;

 /* Crea segmento */
 if ((shmid = shmget(key, SHMSIZE, IPC_CREAT | 0666)) < 0) {
 perror("shmget");//describe el error
 exit(1);
 }

 /*Añade segmento . */
 if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
 perror("shmat");
 exit(1);
 }

 printf ("Memoria compartida: listo \n");

////////////////////////////////////////////////////////////////////////////

 scanf("%d", &numero);
 int index;
 for(index=0;index<numero;index++)
{
   flags[index] =-1;
}
 for(index=0;index<numero-1;index++)
{
   turno[index] =0;
}

 /*Pone 1 en primer lugar */
 s=shm;
 *s++='1';
 *s=NULL;
 printf("Process1:- he puesto el mensaje %s\n",shm);
  /*
Espera por otros procesos 
sabe donde comienza y donde acaba
 */
int i;

/* while (*shm != '2' && *shm+6 != 'a')
 sleep(1);
 printf("MENSAJE: %s\n",shm);
 while (*shm != '3' && *shm+7 != 'y')
 sleep(1);
 */
pid_t pid1,pid2;
pid1=0, pid2=0;
interesado[0]=0;
while(interesado[0]<numero)
      {
	//while(1){
	  /*if(pid1==0)
	  {
	  pid1=fork();
	  
	  }*/
	  /*entrar(i);
	  
	  salir(i);*/
	  sleep(3);//interesado[0]++
	  printf("\n MENSAJE: %s\n",shm);
	}

	shmdt ((char *)interesado);
	shmctl (id_zone3 , IPC_RMID, (struct shmid_ds *)NULL);
	
	shmdt ((char *)turno);
	shmctl (id_zone1, IPC_RMID, (struct shmid_ds *)NULL);
	
	shmdt ((char *)shm);
	shmctl (shmid, IPC_RMID, (struct shmid_ds *)NULL);	
	
	shmdt ((char *)flags);
	shmctl (id_zone0, IPC_RMID, (struct shmid_ds *)NULL);
 /*printf("Process1:- Process2 ha puesto el mensaje %s\n",shm);
 while (*shm != '3' && *shm+7 != 'y')
 sleep(1);

 printf("Process1:- Process3 ha puesto el mensaje %s\n",shm);*/
 printf("Process1:- Termino, cerrando...\n");
 exit(0);
}