Ejemplo n.º 1
0
QDataStream &operator<<(QDataStream &out, const ValuesChangedCommand &command)
{
    static const bool dontUseSharedMemory = !qgetenv("DESIGNER_DONT_USE_SHARED_MEMORY").isEmpty();

    if (!dontUseSharedMemory && command.valueChanges().count() > 5) {
        static quint32 keyCounter = 0;
        ++keyCounter;
        command.m_keyNumber = keyCounter;
        QByteArray outDataStreamByteArray;
        QDataStream temporaryOutDataStream(&outDataStreamByteArray, QIODevice::WriteOnly);
        temporaryOutDataStream.setVersion(QDataStream::Qt_4_8);

        temporaryOutDataStream << command.valueChanges();;

        QSharedMemory *sharedMemory = createSharedMemory(keyCounter, outDataStreamByteArray.size());

        if (sharedMemory) {
            std::memcpy(sharedMemory->data(), outDataStreamByteArray.constData(), sharedMemory->size());
            out << command.keyNumber();
            return out;
        }
    }

    out << qint32(0);
    out << command.valueChanges();

    return out;
}
Ejemplo n.º 2
0
void PlaybackController::daemon() {
	PlaylistService* playlist_service = new PlaylistService( dao_factory );
	MetadataService* metadata_service = new MetadataService( dao_factory );

	createSharedMemory();

	shm_obj->truncate( sizeof( SharedData) );
	boost::interprocess::mapped_region region (
			*shm_obj,
			boost::interprocess::read_write
			);
	SharedData* shared_data = static_cast<SharedData*>(region.get_address());

	while( 1 ) {
		g_debug( "Playing a tune" );

		long track_id = playlist_service->getCurrentTrackId();
		Track* current_track = metadata_service->getTrackById( track_id );
		current_track->print();
		metadata_service->free( current_track );

		timespec sleep_time = {2, 0 };
		nanosleep( &sleep_time, NULL );

		playlist_service->cueNextTrack();
		playlist_service->saveState();
	}

	delete metadata_service;
	delete playlist_service;
}
Ejemplo n.º 3
0
int createSharedScene(NBodyState* st, const NBodyCtx* ctx, const char* inputFile)
{
    key_t key;
    size_t size;
    int shmId = -1;

    size = sizeof(scene_t) + st->nbody * sizeof(FloatPos);
    key = DEFAULT_SHMEM_KEY;
    //key = ftok(inputFile, getpid());
    if (key < 0)
    {
        key = DEFAULT_SHMEM_KEY;
        perror("Error getting key");
        return 1;
    }

    st->scene = (scene_t*) createSharedMemory(key, size, &shmId);
    if (!st->scene)
        return 1;

    st->shmId = shmId;
    prepareSceneFromState(ctx, st);

    return 0;
}
Ejemplo n.º 4
0
int main(int argc, char **argv)
{
	createSharedMemory();
	ipcon_create(&MyIP);
    // Connect to brickd
    if(ipcon_connect(&MyIP, HOST, PORT) < 0) {
        fprintf(stderr, "Could not connect to brickd\n");
        exit(1);
    }


	getTinker();
	sleep(2);   // Es dauert etwas, bis die Enumeration der Devices durch ist, also warten !!!

	if ( tinkerCounter <= 0 ) {
		fprintf(stderr,"Kein Gerät vorhanden ");
		exit(2);
	}

	curses_init();
	showSystem(1);
	// Threads für die Anzeige erstellen
	tf1_init();
	getchar();

	curses_end();
	deleteSharedMemory();
	return (0);
}
Ejemplo n.º 5
0
int main() {
	int shmId = createSharedMemory();

	if(shmId == -1) {
		perror("Could not create shared memory");
		return 1;
	}

	Buffer* buffer;

	if(sharedBufferInit(shmId, &buffer, BUFFERSIZE)) {
		perror("Could not initialize buffer");
		return 1;
	}

	fprintf(stderr, "%d", shmId);

	sigset_t sigset;
	int sig;

	sigemptyset(&sigset);
    sigaddset(&sigset, SIGUSR1);
	sigprocmask(SIG_BLOCK, &sigset, NULL);

	printf("[%s] Producer is ready. Waiting for SIGUSR1 to PID=%d.\n", getTime(), getpid());

	sigwait(&sigset, &sig);

	generateData(buffer);

	destroySharedMemory(shmId);

	return 0;
}
Ejemplo n.º 6
0
Archivo: p1.c Proyecto: mprashantm/CN
int main()
{
    int key1=ftok(".",1);
    int key2=ftok(".",2);
    int key3=ftok(".",3);
    printf("%d %d %d",key1,key2,key3);
    int semid =createSemaphore(key1,2);//S1 S2
    int shmid1=createSharedMemory(key2,10);//x
    printf("shmid1 %d from main\n",shmid1);
    char *X   =(char *)attachSharedMemory(shmid1); 
//    int shmid2=createSharedMemory(key3,10);//y
  //  printf("shmid2 %d from main\n",shmid2);
    char *Y  ; //=//(char *)attachSharedMemory(shmid2);
    int *values=(int *)malloc(sizeof(int *)*2);
    *values=0;*(values+1)=0;
    initSemaphore(semid,values);
/*    V(semid,0);
    printf("hi");
    P(semid,0);
*/   
    int x=0,y=0,i;
    while(1)
	{
	 // write(x)
 	  i=0;
	  printf("P1 X=%d Y=%d\n",x,y);
          while(x>0)
		{
		  *X=x%10-'0';x/=10;X++;i++;
		}
	  printf("*\n");
	  *X='\0';
	  printf("*\n");
	  X-=i;//X Points to start of shared memory  	
	 //V(1)
          V(semid,0);
	 //P(2)
	  P(semid,1);
	 //Read Y
          i=0;
	  while(*Y!='\0')
		{
		   y=y*10+(*Y+'0');Y++;i++;
		}
	  Y-=i; 
	 //X=Y+1;
	  x=y+1;	
	   printf("P1 X=%d Y=%d\n",x,y);
	}
} 
Ejemplo n.º 7
0
void Server::initServer(int port){
	createSharedMemory();
	int id = fork();

	struct stat st;
	if (stat(FIFO_NAME, &st) != 0)
		mkfifo(FIFO_NAME, 0666);

	if(id > 0){
		initSocket(port);
		wait();
	}
	else if (id == 0){
		consumeData();
	}
}
bool CrashHandlerImpl::initialize() {
	Autolock autoLock(&m_Lock);
	
	bool initialized = true;
	
	m_CrashHandlerPath = platform::getHelperExecutable(m_CrashHandlerApp);
	
	if(!createSharedMemory()) {
		return false;
	}
	
	fillBasicCrashInfo();
	
	if(!registerCrashHandlers()) {
		destroySharedMemory();
		initialized = false;
	}

	return initialized;
}
Ejemplo n.º 9
0
bool CrashHandlerImpl::initialize() {
	Autolock autoLock(&m_Lock);
	
	bool initialized = true;
	
	fs::path local_path = fs::path(getExecutablePath());
	if(!local_path.empty()) {
		local_path = local_path.parent() / m_CrashHandlerApp;
		if(fs::exists(local_path)) {
			m_CrashHandlerPath = local_path;
		}
	}
	if(m_CrashHandlerPath.empty()) {
		local_path = m_CrashHandlerApp;
		if(fs::exists(local_path)) {
			m_CrashHandlerPath = local_path;
		}
	}
	if(fs::libexec_dir && m_CrashHandlerPath.empty()) {
		local_path = fs::path(fs::libexec_dir) / m_CrashHandlerApp;
		if(fs::exists(local_path)) {
			m_CrashHandlerPath = local_path;
		}
	}
	
	if(!createSharedMemory()) {
		return false;
	}
	
	fillBasicCrashInfo();
	
	if(!registerCrashHandlers()) {
		destroySharedMemory();
		initialized = false;
	}

	return initialized;
}
Ejemplo n.º 10
0
int main(int argc, char ** argv)
{
    numberOfPhilosophers = atoi(argv[1]);
    cnts = malloc(numberOfPhilosophers * sizeof(int));
    pids = malloc(numberOfPhilosophers * sizeof(int));
    pid_t t;
    beginPosOfStick = malloc(numberOfPhilosophers * sizeof(int));
    while (1)
    {
        int correctBegin = 0;
        for (int i = 0; i < numberOfPhilosophers; ++i)
            beginPosOfStick[i] = (i - rand() % 2 + numberOfPhilosophers) % numberOfPhilosophers;
        for (int i = 0; i < numberOfPhilosophers; ++i)
            if (beginPosOfStick[i] == i && beginPosOfStick[(i + 1) % numberOfPhilosophers] == i)
                correctBegin = 1;
        if (correctBegin)
            break;
    }
    for (int i = 0; i < numberOfPhilosophers; ++i)
        printf("stick #%d is in philosopher's #%d hands\n", i, beginPosOfStick[i]);
    createSharedMemory();
    for (philosopherNumber = 0; philosopherNumber < numberOfPhilosophers - 1; ++philosopherNumber)
    {
        t = fork();
        if (t == 0)
            break;
        else
            pid[philosopherNumber] = t;
    }
    if (philosopherNumber == numberOfPhilosophers - 1)
        pid[numberOfPhilosophers - 1] = getpid();
    solve();
    free(cnts);
    free(pids);
    return 0;
}
Ejemplo n.º 11
0
Archivo: ex3.c Proyecto: dodgerDojo/Ex3
int main(int argc, char *argv[])
{
    const unsigned int EXPECTED_ARGC = 2;
    const unsigned int KEY_FILE_ARG_INDEX = 1;
    const unsigned char KEY_CHAR = 'H';

    const char ENDLINE[] = "\n";
    const char SEPERATOR[] = ",";

    key_t key = 0;
    char *shm_addr = NULL;
    int csv_fd = 0, queue_length = 0, shm_id = 0, sem_id = 0;
    int job_number = 0, rel_prio = 0, real_prio = 0;

    initSigactions();

    // Initialize the rand() seed.
    srand(time(NULL));

    if(argc != EXPECTED_ARGC)
    {
        // No checking needed, exits with error code.
        write(STDERR_FILENO, NOF_INPUTS_ERROR, sizeof(NOF_INPUTS_ERROR));
        exit(EXIT_ERROR_CODE);
    }

    // Create fifo.
    if(mkfifo(FIFO_NAME, ALLOW_READ_WRITE_TO_ALL) < 0)
    {
        // No checking needed, exits with error code.
        write(STDERR_FILENO, MKFIFO_ERROR, sizeof(MKFIFO_ERROR));
        exit(EXIT_ERROR_CODE);
    }

    writePidToFifo();

    // Wait for the queue process' singal.
    waitForSignal();

    printf("got signal from %d!\n", Queue_Pid);

    // Generate key from the given file
    key = ftok(argv[KEY_FILE_ARG_INDEX], KEY_CHAR);

    if(key < 0)
    {
        deleteFifo();
        // No checking needed, exits with error code.
        write(STDERR_FILENO, FTOK_ERROR, sizeof(FTOK_ERROR));
        exit(EXIT_ERROR_CODE);       
    }

    // Create shared memory.
    shm_addr = createSharedMemory(key, &shm_id);

    // Create semaphore.
    sem_id = createBinarySemaphore(key, shm_id);

    // Notify the queue.out process.
    if(kill(Queue_Pid, SIGUSR1) < 0)
    {
        deleteFifo();
        // No checking needed, exits with error code.
        write(STDERR_FILENO, KILL_ERROR, sizeof(KILL_ERROR) - 1);
        exit(EXIT_ERROR_CODE);
    }

    queue_length = readQueueLengthFromFifo();

    printf("Got N: %d\n", queue_length);

    // Done using the fifo - delete it.
    deleteFifo();

    // Game Started!
    handleGame(shm_id, shm_addr, sem_id, queue_length, &job_number, \
               &rel_prio, &real_prio);

    deleteResources(shm_id, sem_id);

    // Write results
    csv_fd = open(CSV_FILE_PATH, O_CREAT | O_APPEND | O_RDWR, ALLOW_READ_WRITE_TO_ALL);
    if(csv_fd < 0)
    {
        // No checking needed, exits with error code.
        write(STDERR_FILENO, OPEN_ERROR, sizeof(OPEN_ERROR) - 1);
        exit(EXIT_ERROR_CODE); 
    }


    writeIntWithEnding(csv_fd, queue_length, SEPERATOR);
    writeIntWithEnding(csv_fd, job_number, SEPERATOR);
    writeIntWithEnding(csv_fd, rel_prio, SEPERATOR);
    writeIntWithEnding(csv_fd, real_prio, ENDLINE);

    return EXIT_OK_CODE;
}
Ejemplo n.º 12
0
void writeEncDecLog(int syslogType, eCRYPT_LOG_MESSAGE logMessage, void* data)
{
	if( IS_SUCCESS )
	{
		if( logMessage == eCryptLogMessage_Allow )
			*IS_SUCCESS = true;
		else
			*IS_SUCCESS = false;
	}

	void* logSM = getSharedMemory(LOG_SHARED_MEMORY_KEY, LOG_SHARED_MEMORY_SIZE);

	if( logSM == NULL )
		logSM = createSharedMemory(LOG_SHARED_MEMORY_KEY, LOG_SHARED_MEMORY_SIZE);

	char dbsLogBuf[256] = {'\0', };

	size_t logSMLength = strlen((char*)logSM);

	bool isFind = false;

	int dbsLogReplaceIndex = 0;
	int dbsLogCnt = 0;
	char** dbsLog = strSplitWithLength(logSM, logSMLength, LINE_SPLIT_STR, &dbsLogCnt);
	for(int i = 0 ; i < dbsLogCnt ; ++i)
	{
		if( i > 0 )
			dbsLogReplaceIndex += strlen(LINE_SPLIT_STR);

		int logDataCnt = 0;
		int logDataLength = strlen(dbsLog[i]);
		char** logData = strSplitWithLength(dbsLog[i], logDataLength, LOG_SPLIT_STR, &logDataCnt);

		char* smLogThreadID = logData[1];
		int smLogType = atoi(logData[2]);
		char* smLogAccessIP = logData[3];
		char* smLogAccessUser = logData[4];
		char* smLogProgramName = logData[5];

		int smLogMessage = atoi(logData[6]);

		int smLogCnt = atoi(logData[7]);

		if( memcmp(LOG_THREAD_ID, smLogThreadID, LOG_THREAD_ID_LENGTH) != 0 ||
			LOG_TYPE != smLogType ||
			memcmp(LOG_ACCESS_IP, smLogAccessIP, LOG_ACCESS_IP_LENGTH) != 0 ||
			memcmp(LOG_ACCESS_USER, smLogAccessUser, LOG_ACCESS_USER_LENGTH) != 0 ||
			memcmp(LOG_PROGRAM_NAME, smLogProgramName, LOG_PROGRAM_NAME_LENGTH) != 0 ||
			smLogMessage != logMessage )
		{
			dbsLogReplaceIndex += logDataLength;

			freeSplit(logData, logDataCnt);
			continue;
		}
		else
		{
			if( smLogMessage == eCryptLogMessage_Over_Behavior && strcmp((char*)data, logData[8]) != 0 )
			{
				dbsLogReplaceIndex += logDataLength;

				freeSplit(logData, logDataCnt);
				continue;
			}
		}

		isFind = true;

		sprintf(dbsLogBuf, "%d%s%s%s%d%s%s%s%s%s%s%s%d%s%d"
			, syslogType, LOG_SPLIT_STR
			, LOG_THREAD_ID, LOG_SPLIT_STR
			, LOG_TYPE, LOG_SPLIT_STR
			, LOG_ACCESS_IP, LOG_SPLIT_STR
			, LOG_ACCESS_USER, LOG_SPLIT_STR
			, LOG_PROGRAM_NAME, LOG_SPLIT_STR
			, logMessage, LOG_SPLIT_STR
			, smLogCnt + 1);

		if( logMessage == eCryptLogMessage_Over_Behavior )
		{
			char dataBuf[64] = {'\0', };
			sprintf(dataBuf, "%s%s", LOG_SPLIT_STR, (char*)data);
			strcat(dbsLogBuf, dataBuf);
		}

		char* dbsFinalLog = replaceIndexWithLength(logSM, dbsLogReplaceIndex, logSMLength, dbsLog[i], dbsLogBuf);

		writeSharedMemory(logSM, dbsFinalLog);

		free(dbsFinalLog);

		freeSplit(logData, logDataCnt);
		break;
	}
	freeSplit(dbsLog, dbsLogCnt);

	if( !isFind )
	{
		sprintf(dbsLogBuf, "%s%d%s%s%s%d%s%s%s%s%s%s%s%d%s%d"
			, ( dbsLogCnt > 0 ) ? LINE_SPLIT_STR : ""
			, syslogType, LOG_SPLIT_STR
			, LOG_THREAD_ID, LOG_SPLIT_STR
			, LOG_TYPE, LOG_SPLIT_STR
			, LOG_ACCESS_IP, LOG_SPLIT_STR
			, LOG_ACCESS_USER, LOG_SPLIT_STR
			, LOG_PROGRAM_NAME, LOG_SPLIT_STR
			, logMessage, LOG_SPLIT_STR
			, 1);

		if( logMessage == eCryptLogMessage_Over_Behavior )
		{
			char dataBuf[64] = {'\0', };
			sprintf(dataBuf, "|%s", (char*)data);
			strcat(dbsLogBuf, dataBuf);
		}

		strcat(logSM, dbsLogBuf);
	}

	releaseSharedMemory(logSM);
}
Ejemplo n.º 13
0
/**
 * Creates/open a shared memory region
 * 
 * The rootname will uniquely identify the shared memory region, 
 * and is valid across different JVM instance. 
 * 
 * The shared memory region should persist across process, until OS reboots 
 * or destroy call is being made.
 * 
 * @param[in] portLibrary The port Library
 * @param[out] handle This handle is required for further attach/destroy of the memory region
 * @param[in] rootname Shared name for the region, which used to identify the region. 
 * @param[in] size Size of the region in bytes
 * @param[in] perm permission for the region.
 * 
 * @return
 * \arg HYPORT_ERROR_SHMEM_OPFAILED Failure - Cannot open the shared memory region
 * \arg HYPORT_INFO_SHMEM_OPENED Success - Existing memory region has been opened
 * \arg HYPORT_INFO_SHMEM_CREATED Success - A new shared memory region has been created
 * 
 */
IDATA VMCALL
hyshmem_open (HyPortLibrary * portLibrary, struct hyshmem_handle **handle,
              const char *rootname, I_32 size, I_32 perm)
{
  /*TODO: Do we need the length to be longer? */
  char controlFile[HYSH_MAXPATH];
  IDATA retryCount, exist;
  key_t fkey;
  void *region;
  int retry = RETRY_COUNT;

  Trc_PRT_shmem_hyshmem_open_Entry (rootname, size, perm);

  if (ensureDirectory (portLibrary) == FAILED)
    {
      portLibrary->error_set_last_error (portLibrary, errno,
                                         HYPORT_ERROR_SHMEM_DATA_DIRECTORY_FAILED);
      Trc_PRT_shmem_hyshmem_open_Exit3 ();
      return HYPORT_ERROR_SHSEM_OPFAILED;
    }

  getControlFilePath (portLibrary, controlFile, HYSH_MAXPATH, rootname);

  while (retry)
    {
      I_32 rc;

      rc = portLibrary->file_attr (portLibrary, controlFile);
      if (HyIsFile != rc)
        {
          Trc_PRT_shmem_hyshmem_open_Event1 (controlFile);
          rc =
            createSharedMemory (portLibrary, handle, controlFile, size, perm);
        }
      else
        {
          Trc_PRT_shmem_hyshmem_open_Event2 (controlFile);
          rc = openSharedMemory (portLibrary, handle, controlFile);
        }

      switch (rc)
        {
        case RETRY:
          Trc_PRT_shmem_hyshmem_open_Event3 (retry);
          retry--;
          usleep (100);
          continue;
        case FAILED:
          Trc_PRT_shmem_hyshmem_open_Exit1 ();
          return HYPORT_ERROR_SHMEM_OPFAILED;
        default:
          Trc_PRT_shmem_hyshmem_open_Exit (rc, *handle);
          return rc;
        }
    }

  /* max number of retry count reach, return failure */
  portLibrary->file_unlink (portLibrary, controlFile);
  Trc_PRT_shmem_hyshmem_open_Exit2 ();
  return HYPORT_ERROR_SHMEM_OPFAILED;
}
Ejemplo n.º 14
0
JNIEXPORT jboolean JNICALL
Java_com_sun_media_renderer_video_XLibRenderer_xlibSetOutputSize(JNIEnv *env,
								  jobject blitter,
								  jint outWidth,
								  jint outHeight)
{
    /* We assume that this function is called only if there is a size change */
    XlibBlitter *xblitter = (XlibBlitter*) GetIntField(env, blitter, "blitter");
    int inWidth = xblitter->inWidth;
    int inHeight = xblitter->inHeight;
    int stride   = xblitter->inStride;

    awtLock(env, xblitter);
    
    /* Get rid of the old image and arrays */
    if (xblitter->ximage) {
	/* Clean up shared memory */
	if (xblitter->shmActive) {
	    destroySharedMemory(xblitter);
	}
	xblitter->ximage->data = NULL;
	XDestroyImage(xblitter->ximage);
    }

    if (xblitter->scaledData) {
	free(xblitter->scaledData);
	xblitter->scaledData = NULL;
    }
    
    if (xblitter->xincs) {
	free(xblitter->xincs);
	xblitter->xincs = NULL;
    }

    if (xblitter->yincs) {
	free(xblitter->yincs);
	xblitter->yincs = NULL;
    }
    
    xblitter->outWidth = outWidth;
    xblitter->outHeight = outHeight;

    if (  outWidth != xblitter->inWidth ||
	  outHeight != xblitter->inHeight) {
	/* We need to scale */
	xblitter->xincs = (char *) malloc(outWidth * sizeof(char));
	xblitter->yincs = (char *) malloc(outHeight * sizeof(char));

	{
	    int x, y, oldValue, newValue, xtotal;
	    oldValue = 0; xtotal = 0;
	    for (x = 1; x < xblitter->outWidth; x++) {
		newValue = (int)((double)(x * xblitter->inWidth) / outWidth);
		xblitter->xincs[x-1] = newValue - oldValue;
		xtotal += newValue - oldValue;
		oldValue = newValue;
	    }
	    xblitter->xincs[x - 1] = xblitter->inStride - xtotal;
	    oldValue = 0;
	    for (y = 1; y < xblitter->outHeight; y++) {
		newValue = (int)((double)(y * inHeight) / outHeight);
		xblitter->yincs[y-1] = newValue - oldValue;
		oldValue = newValue;
	    }
	}

	stride = outWidth;
    } else {
	/* No scaling required */
	xblitter->xincs = NULL;
	xblitter->yincs = NULL;
	xblitter->scaledData = NULL;
    }

    /* Try to allocate a shared memory image */
    if (xblitter->shmAvailable) {
	createSharedMemory(xblitter, outWidth, outHeight);
    }
    
    /* If a shared memory image could not be created and we need to scale, use XLib */
    if (xblitter->shmActive == 0) {
	if ( outWidth != xblitter->inWidth || outHeight != xblitter->inHeight) {
	    xblitter->scaledData = (void *) malloc(outWidth * outHeight *
						   (xblitter->bitsPerPixel >> 3));
	}

	xblitter->ximage = XCreateImage(xblitter->display, xblitter->visual,
					xblitter->depth, ZPixmap, 0,
					(char *)0, outWidth, outHeight,
					xblitter->bitsPerPixel,
					stride * (xblitter->bitsPerPixel >> 3));
    }