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

C++ shmget函数代码示例

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

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



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

示例1: unlinkPool

/*
 * A fix which unlinks all segments for the given name.
 * I don't know where to put this routine, maybe it fits better in rt_pool.c.
 */
static void
unlinkPool(
  const char *name
){
  int 	 i;
  int    fd;                                              
  int    flags = O_RDWR;              
  mode_t mode  = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP; 
  key_t  key;
  int    shm_id;
  struct shmid_ds   ds;

  char   *str = getenv(pwr_dEnvBusId);
  char   segname[128];
  char	 busid[8];

  strncpy(busid, (str ? str : "XXX"), 3);
  busid[3] = '\0';

  sprintf(segname, "%s_%.3s", name, busid);

  /* This is the only way I know to find out if the memory is created, ML */
#if defined OS_LYNX
  fd = shm_open(segname, flags, mode); 
#else
  fd = open(segname, flags, mode); 
#endif
  if (fd != -1) { 
    close(fd);

#if defined OS_LYNX
      shm_unlink(segname);
#else
      key    = ftok(segname, 'P');
      shm_id = shmget(key, 0, 0660);
      shmctl(shm_id, IPC_RMID, &ds);

      unlink(segname);
#endif

    for (i = 1; TRUE; i++) {
      sprintf(segname, "%.11s%04d_%.3s", name, i, busid);
#if defined OS_LYNX
      fd = shm_open(segname, flags, mode); 
#else
      fd = open(segname, flags, mode); 
#endif

      if (fd == -1)
        break;

      close(fd);

#if defined OS_LYNX
      shm_unlink(segname);
#else
      key    = ftok(segname, 'P');
      shm_id = shmget(key, 0, 0660);
      shmctl(shm_id, IPC_RMID, &ds);

      unlink(segname);
#endif

    }
  }
}
开发者ID:Strongc,项目名称:proview,代码行数:70,代码来源:rt_gdb.c


示例2: m_syncData

VstSyncController::VstSyncController() :
	m_syncData( NULL ),
	m_shmID( -1 ),
	m_shm( "/usr/bin/lmms" )
{
	if( ConfigManager::inst()->value( "ui", "syncvstplugins" ).toInt() )
	{
		connect( Engine::mixer(), SIGNAL( sampleRateChanged() ), this, SLOT( updateSampleRate() ) );

#ifdef USE_QT_SHMEM
		if ( m_shm.create( sizeof( VstSyncData ) ) )
		{
			m_syncData = (VstSyncData*) m_shm.data();
		}
		else
		{
			qWarning() << QString( "Failed to allocate shared memory for VST sync: %1" ).arg( m_shm.errorString() );
		}
#else
		key_t key; // make the key:
		if( ( key = ftok( VST_SNC_SHM_KEY_FILE, 'R' ) ) == -1 )
		{
				qWarning( "VstSyncController: ftok() failed" );
		}
		else
		{	// connect to shared memory segment
			if( ( m_shmID = shmget( key, sizeof( VstSyncData ), 0644 | IPC_CREAT ) ) == -1 )
			{
				qWarning( "VstSyncController: shmget() failed" );
			}
			else
			{		// attach segment
				m_syncData = (VstSyncData *)shmat( m_shmID, 0, 0 );
				if( m_syncData == (VstSyncData *)( -1 ) )
				{
					qWarning( "VstSyncController: shmat() failed" );
				}
			}
		}
#endif
	}
	else
	{
		qWarning( "VST sync support disabled in your configuration" );
	}

	if( m_syncData == NULL )
	{
		m_syncData = new VstSyncData;
		m_syncData->hasSHM = false;
	}
	else
	{
		m_syncData->hasSHM = true;
	}

	m_syncData->isPlaying = false;
	m_syncData->m_bufferSize = Engine::mixer()->framesPerPeriod();
	m_syncData->timeSigNumer = 4;
	m_syncData->timeSigDenom = 4;

	updateSampleRate();
}
开发者ID:Penguinum,项目名称:lmms,代码行数:63,代码来源:VstSyncController.cpp


示例3: main


//.........这里部分代码省略.........

                if (!strcmp(input, "exit"))
                {
                    ReleaseSemaphore(serverSemaphore, 1, NULL);
                    CloseHandle(clientSemaphore);
                    free(buffer);
                    return 0;
                }
            }
            ReleaseSemaphore(serverSemaphore, 1, NULL);
        }
        return 0;
    }

#elif __linux__
    pid_t pid;
    key_t key = ftok("/home/", 0);

    struct sembuf serverSemaphore;
    struct sembuf clientSemaphore;
    int semaphoreId;

    int sharedMemoryId;
    char *segmentPtr;

    if (argc != 2)
    {
        switch (pid = fork())
        {
        case -1:
            printf("Can't fork process %d\n", pid);
            break;
        case 0:
            execlp("gnome-terminal", "gnome-terminal", "-x", argv[0], "1", NULL);
        default:
            if ((sharedMemoryId = shmget(key, 1024, IPC_CREAT | IPC_EXCL | 0660)) == -1)
            {
                if ((sharedMemoryId = shmget(key, 1024, 0)) == -1)
                {
                    printf("error\n");
                    exit(1);
                }
            }

            if ((segmentPtr = (char*)shmat(sharedMemoryId, NULL, 0)) == (char*)(-1))
            {
                printf("Can't attach shared memory\n");
                exit(1);
            }

            semaphoreId = semget(key, 1, 0666 | IPC_CREAT);

            if (semaphoreId < 0)
            {
                printf("Can't get semaphore\n");
                exit(EXIT_FAILURE);
            }

            if (semctl(semaphoreId, 0, SETVAL, (int)0) < 0)
            {
                printf("Can't initialize semaphore\n");
                exit(EXIT_FAILURE);
            }

            serverSemaphore.sem_num = 0;
            serverSemaphore.sem_op = 0;
            serverSemaphore.sem_flg = 0;

            printf("Server process: ");

            while (1) {
                char *message = NULL;
                message = (char*)malloc(1024 * sizeof(char));

                semop(semaphoreId, &serverSemaphore, 1);

                printf("\nInput message to client: ");
                fflush(stdin);
                cin >> message;

                strcpy(segmentPtr, message);

                serverSemaphore.sem_op = 3;
                semop(semaphoreId, &serverSemaphore, 1);

                serverSemaphore.sem_op = 0;
                semop(semaphoreId, &serverSemaphore, 1);

                if (!strcmp("exit", message))
                    return 0;

                strcpy(message, segmentPtr);
                printf("Client message: %s\n", message);
            }
            return 0;
        }
    }
    else
    {
        if ((sharedMemoryId = shmget(key, 1024, IPC_CREAT | IPC_EXCL | 0660)) == -1)
开发者ID:BSUIR450503,项目名称:450503_mischenko,代码行数:101,代码来源:Main.cpp


示例4: main

int main(int argc, char **argv)
{
    int init_db = 0, i;
#ifdef _WIN32
    HANDLE *pids;
#else
    pid_t *pids;
#endif

    for (i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-clients") == 0) {
	    if (i + 1 < argc) {
	        i++;
		n_clients = strtol(argv[i], NULL, 0);
	    }
        } else if (strcmp(argv[i], "-dbname") == 0) {
	    if (i + 1 < argc) {
	        i++;
		dbname = argv[i];
	    }
        } else if (strcmp(argv[i], "-tpc") == 0) {
	    if (i + 1 < argc) {
	        i++;
		n_txn_per_client = strtol(argv[i], NULL, 0);
	    }
        } else if (strcmp(argv[i], "-init") == 0) {
            init_db = 1;
        } else if (strcmp(argv[i], "-tps") == 0) {
	    if (i + 1 < argc) {
	        i++;
		tps = strtol(argv[i], NULL, 0);
	    }
        } else if (strcmp(argv[i], "-v") == 0) {
	    verbose++;
	} else if (strcmp(argv[i], "-excl") == 0) {
	    useexcl++;
	}
    }
    if (dbname == NULL) {
        fprintf(stderr, "usage: %s -dbame DBFILE [-v] [-init] "
		"[-tpc n] [-clients c] [-excl\n\n", argv[0]);
        fprintf(stderr, "-v        verbose error messages\n");
        fprintf(stderr, "-init     initialize the tables\n");
        fprintf(stderr, "-tpc      transactions per client\n");
        fprintf(stderr, "-clients  number of simultaneous clients\n");
	fprintf(stderr, "-excl     use EXCLUSIVE transactions\n");
	exit(1);
    }

    fprintf(stdout, "Scale factor value: %d\n", tps);
    fprintf(stdout, "Number of clients: %d\n", n_clients);
    fprintf(stdout, "Number of transactions per client: %d\n\n",
	    n_txn_per_client);
    fflush(stdout);

    if (useexcl) {
	combegtrans = "COMMIT TRANSACTION ; BEGIN EXCLUSIVE TRANSACTION";
	begtrans = "BEGIN EXCLUSIVE TRANSACTION";
    }

    if (init_db) {
        fprintf(stdout, "Initializing dataset...\n");
	createDatabase();
        fprintf(stdout, "done.\n\n");
	fflush(stdout);
    }

#ifndef _WIN32
    shmid = shmget(IPC_PRIVATE, 200 * sizeof (int), IPC_CREAT | 0666);
    shm = shmat(shmid, NULL, 0);
#endif
    transaction_count = &shm[0];
    failed_transactions = &shm[1];
    stat_counts = &shm[2];
    *transaction_count = 0;
    *failed_transactions = 0;
    memset(stat_counts, 0, 198 * sizeof (int));

#ifdef _WIN32
    pids = malloc(n_clients * sizeof (HANDLE));
#else
    pids = malloc(n_clients * sizeof (pid_t));
#endif
    if (pids == NULL) {
        fprintf(stderr, "malloc failed\n");
	exit(2);
    }

    fprintf(stdout, "Starting Benchmark Run\n");

    transactions = 0;
#ifdef _WIN32
    start_time = GetTickCount();
#else
    gettimeofday(&start_time, NULL);
#endif
    if (n_clients < 2) {
        runClientThread(NULL);
    } else {
#ifdef _WIN32
//.........这里部分代码省略.........
开发者ID:Distrotech,项目名称:sqliteodbc,代码行数:101,代码来源:sbench.c


示例5: sysv_runtime_query

/* ////////////////////////////////////////////////////////////////////////// */
static int
sysv_runtime_query(mca_base_module_t **module,
                   int *priority,
                   const char *hint)
{
    char c     = 'j';
    int shmid  = -1;
    char *a    = NULL;
    char *addr = NULL;
    struct shmid_ds tmp_buff;
    int flags;
    int ret;

    ret = OSHMEM_SUCCESS;

    *priority = 0;
    *module = NULL;

    /* if we are here, then let the run-time test games begin */

#if defined (SHM_HUGETLB)
    if (mca_sshmem_sysv_component.use_hp != 0) {
         flags = IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR | SHM_HUGETLB;
        if (-1 == (shmid = shmget(IPC_PRIVATE, sshmem_sysv_gethugepagesize(), flags))) {
            if (mca_sshmem_sysv_component.use_hp == 1) {
                mca_sshmem_sysv_component.use_hp = 0;
                ret = OSHMEM_ERR_NOT_AVAILABLE;
                goto out;
            }
            mca_sshmem_sysv_component.use_hp = 0;
        }
        else if ((void *)-1 == (addr = shmat(shmid, NULL, 0))) {
            shmctl(shmid, IPC_RMID, NULL);
            if (mca_sshmem_sysv_component.use_hp == 1) {
                mca_sshmem_sysv_component.use_hp = 0;
                ret = OSHMEM_ERR_NOT_AVAILABLE;
                goto out;
            }
            mca_sshmem_sysv_component.use_hp = 0;
        }
    }
#else
    if (mca_sshmem_sysv_component.use_hp == 1) {
        mca_sshmem_sysv_component.use_hp = 0;
        ret = OSHMEM_ERR_NOT_AVAILABLE;
        goto out;
    }
    mca_sshmem_sysv_component.use_hp = 0;
#endif

    if (0 == mca_sshmem_sysv_component.use_hp) {
        flags = IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR;
        if (-1 == (shmid = shmget(IPC_PRIVATE, (size_t)(opal_getpagesize()), flags))) {
            ret = OSHMEM_ERR_NOT_AVAILABLE;
            goto out;
        }
        else if ((void *)-1 == (addr = shmat(shmid, NULL, 0))) {
            shmctl(shmid, IPC_RMID, NULL);
            ret = OSHMEM_ERR_NOT_AVAILABLE;
            goto out;
        }
    }

    /* protect against lazy establishment - may not be needed, but can't hurt */
    a = addr;
    *a = c;

    if (-1 == shmctl(shmid, IPC_RMID, NULL)) {
        goto out;
    }
    else if (-1 == shmctl(shmid, IPC_STAT, &tmp_buff)) {
        goto out;
    }
    /* all is well - rainbows and butterflies */
    else {
        *priority = mca_sshmem_sysv_component.priority;
        *module = (mca_base_module_t *)&mca_sshmem_sysv_module.super;
    }

  out:
    if ((char *)-1 != addr) {
        shmdt(addr);
    }
    return ret;
}
开发者ID:Cai900205,项目名称:test,代码行数:86,代码来源:sshmem_sysv_component.c


示例6: main

int main ( void )
// Mode d'emploi :
//    Gère la création et la destruction de tous les composantes de
//    l'application, et tourne tant que le simulateur n'a pas renvoyé.
//
// Contrat :
//    (Aucun)
//
// Algorithme :
//    Initialise les composantes fournies pour le TP, puis crée tous les
//    mécanismes IPC (sémaphores, files de message et la mémoire partagée).
//    Chaque tâche est ensuite lancée une par une, le simulateur étant
//    lancé en dernier pour éviter que l'utilisateur lance des demandes
//    avant que toute l'application ne soit prête.
//    La tâche tourne ensuite à l'infini tant que le simulateur ne renvoie
//    pas, avant de demander la terminaison de chaque tâche en cours puis
//    la suppression des mécanismes IPC. Finalement, l'affichage est
//    terminé et l'application termine.
//
{
    /* --- Initialisation --- */

    // Initialisation de l'application
#ifdef AFFICHAGE_XTERM
    enum TypeTerminal terminal = XTERM;
#else // AFFICHAGE_XTERM
    enum TypeTerminal terminal = VT220;
#endif // AFFICHAGE_XTERM
    InitialiserApplication(terminal);
    size_t MAX_TACHES = NB_BARRIERES + 2;
    pid_t tachesPid[MAX_TACHES];
    size_t taches = 0;

    // Initialiser les files de message
    int filesId[NB_BARRIERES];
    for (size_t i = 0; i < NB_BARRIERES; i++)
    {
        filesId[i] = msgget(CLE_BARRIERES[i], IPC_CREAT | DROITS);
    }

    // Initialiser le sémaphore du mutex à 1 (car il n'est pas en cours
    // d'utilisation) et les sémaphores des barrières à 0 (car il n'y a aucune
    // requête en cours).
    int semId = semget(CLE_SEMAPHORE, NUM_SEMAPHORES, IPC_CREAT | DROITS);
    semctl(semId, SEM_MUTEX, SETVAL, 1);
    semctl(semId, SEM_PBP, SETVAL, 0);
    semctl(semId, SEM_ABP, SETVAL, 0);
    semctl(semId, SEM_EGB, SETVAL, 0);

    // Initialiser la mémoire partagée avec aucune place occupée et aucune
    // requête envoyée
    int shmId = shmget(CLE_MEMOIRE_PARTAGEE, sizeof(memoire_partagee_t), IPC_CREAT | DROITS);
    memoire_partagee_t * mem = (memoire_partagee_t *) shmat(shmId, NULL, 0);
    mem->placesOccupees = 0;
    for (size_t i = 0; i < NB_PLACES; i++)
    {
        mem->places[i] = PLACE_VIDE;
    }
    for (size_t i = 0; i < NB_BARRIERES_ENTREE; i++)
    {
        mem->requetes[i] = REQUETE_VIDE;
    }
    shmdt(mem);

    // Lancer toutes les tâches
    tachesPid[taches++] = ActiverHeure();
    if ((tachesPid[taches++] = fork()) == 0)
    {
        // Fils - Barrière S (Sortie)
        BarriereSortie(SORTIE_GASTON_BERGER);
    }
    else
    {
        // Père
        if ((tachesPid[taches++] = fork()) == 0)
        {
            // Fils - Barrière Entrée (Blaise Pascal - Profs)
            BarriereEntree(PROF_BLAISE_PASCAL);
        }
        else
        {
            // Père
            if ((tachesPid[taches++] = fork()) == 0)
            {
                // Fils - Barrière Entrée (Blaise Pascal - Autres)
                BarriereEntree(AUTRE_BLAISE_PASCAL);
            }
            else
            {
                // Père
                if ((tachesPid[taches++] = fork()) == 0)
                {
                    // Fils - Barrière Entrée (Gaston Berger)
                    BarriereEntree(ENTREE_GASTON_BERGER);
                }
                else
                {
                    // Père
                    if ((tachesPid[taches++] = fork()) == 0)
                    {
//.........这里部分代码省略.........
开发者ID:Lyrositor,项目名称:insa,代码行数:101,代码来源:Mere.cpp


示例7: main

int main()
{
    int s, namelen,ns;
    struct sockaddr_in client, server;
    struct mensagem buf;
    char bufferer[33];

    
    //memoria = mmap(NULL, sizeof *memoria, PROT_READ | PROT_WRITE,MAP_SHARED | MAP_ANONYMOUS, -1, 0);
    

    size_t shmsize = sizeof(struct data);
    int shmid = shmget(IPC_PRIVATE, shmsize, IPC_CREAT | 0666);
    struct data *data = shmat(shmid, (void *) 0, 0);
    data->count = 0;
    data->doorCounter = 0;
    
    
    
    /*
     * Cria um socket TCP (stream) para aguardar conexıes
     */
    if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0)
    {
        perror("Socket()");
        exit(2);
    }

    
    
    /*
     * Define a qual endereÁo IP e porta o servidor estar· ligado.
     * Porta = 0 -> faz com que seja utilizada uma porta qualquer livre.
     * IP = INADDDR_ANY -> faz com que o servidor se ligue em todos
     * os endereÁos IP
     */
    server.sin_family      = AF_INET;   /* Tipo do endereÁo             */
    server.sin_port        = htons(5000);         /* Escolhe uma porta disponÌvel */
    server.sin_addr.s_addr = INADDR_ANY;/* EndereÁo IP do servidor      */
    

    int on = 1;
    setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
    /*
     * Liga o servidor ‡ porta definida anteriormente.
     */
    if (bind(s, (struct sockaddr *)&server, sizeof(server)) < 0)
    {
        perror("bind()");
        exit(3);
    }
    
    /*
     * Prepara o socket para aguardar por conexıes e
     * cria uma fila de conexıes pendentes.
     */
    //servidor fica esperando conexoes tcps, recebe uma mensagem e depois encerra ela, para que seja capaz
    //de receber outra conexao.
    //printf("pronto para mais");

    if (listen(s, 1) != 0)
    {
        perror("Listen()");
        exit(4);
    }
    

    //servidor fica esperando conexoes tcps, recebe uma conexao abre um fork
    //variaveis para fork
    pid_t pid, fid;
  
    while (1) {

 
        //aceita uma conexao
        namelen = sizeof(client);
        if ((ns = accept(s, (struct sockaddr *)&client, &namelen)) == -1)
        {
            //perror("Accept()");
            
            //exit(5);
        }
        
        
        if ((pid = fork()) == 0) {
            /*
             * Processo filho
             */
            
            /* Fecha o socket aguardando por conexıes */
            close(s);
            
            /* Processo filho obtem seu prÛprio pid */
            fid = getpid();
            
            /* Recebe uma mensagem do cliente atravÈs do novo socket conectado */
         
            
            
            if(recv(ns, &bufferer, sizeof(bufferer), 0) == -1)
//.........这里部分代码省略.........
开发者ID:rogerluan,项目名称:Redes-A-PUC-Campinas-2016,代码行数:101,代码来源:TCPServidor.c


示例8: main

int main(void)
{
	signed int *X;
	pid_t pid1, pid2;
	int shmid, i, status;

	struct sembuf pop, vop ;

	int semid1, semid2;

	semid1 = semget(IPC_PRIVATE, 1, 0777|IPC_CREAT);
	semid2 = semget(IPC_PRIVATE, 1, 0777|IPC_CREAT);

	semctl(semid1, 0, SETVAL, 0);
	semctl(semid2, 0, SETVAL, 1);

	pop.sem_num = vop.sem_num = 0;
	pop.sem_flg = vop.sem_flg = 0;
	pop.sem_op = -1 ; vop.sem_op = 1 ;

	shmid = shmget(IPC_PRIVATE, 1*sizeof(signed int), 0777|IPC_CREAT);
	X = (signed int *)shmat(shmid, 0, 0);
	*X = 0;
	
	pid1 = fork();
	pid2 = fork();

	if(pid1 == 0 && pid2 != 0)
	{
		P(semid1);
		for( i = 0; i < 10; i++)
		{
			*X += 1;
			if( i == 4 )
				sleep(1);
			printf("\nIncrementing");
		}
		shmdt(X);
		V(semid2);
		return 0;
	}
	if(pid2 == 0 && pid1 != 0)
	{
		P(semid2);
		for( i = 0; i < 10; i++)
		{
			*X -= 1;
			printf("\nDecrementing");
		}
		shmdt(X);
		V(semid1);
		return 0;
	}
	if(pid1 == 0 && pid2 == 0)
		return 0;
	
	for( i = 0; i < 3; i++)
		wait(&status);
	
	printf("\nValue of X = %d\n", *X);

	shmdt(X);
	shmctl(shmid, IPC_RMID, 0);	
	
	semctl(semid1, 0, IPC_RMID, 0);
	semctl(semid2, 0, IPC_RMID, 0);

	return 0;
}
开发者ID:anki08,项目名称:codes,代码行数:69,代码来源:6part2.c


示例9: main


//.........这里部分代码省略.........
		    dlopen("libapi.so", RTLD_NOW | RTLD_GLOBAL)) == NULL) {
			fprintf(stderr,
			    catgets(catfd, SET, 2483,
			    "The shared object library %s cannot "
			    "be loaded: %s"), "libapi.so", dlerror());
			fprintf(stderr, "\n");
			exit(1);
		}
		dl_acs_status =
		    (ACS_STAT()) map_sym(api_handle, "acs_status");
		dl_acs_query_pool =
		    (ACS_QP()) map_sym(api_handle, "acs_query_pool");
		dl_acs_query_scratch =
		    (ACS_QS()) map_sym(api_handle, "acs_query_scratch");
		dl_acs_response =
		    (ACS_RSP()) map_sym(api_handle, "acs_response");
		dl_acs_set_access =
		    (ACS_SA()) map_sym(api_handle, "acs_set_access");
		dl_acs_set_scratch =
		    (ACS_SS()) map_sym(api_handle, "acs_set_scratch");
		if (what_pool >= 0 && pool_count < 0)
			pool_count = 10;

		if (pool_count > 0 && what_pool < 0)
			what_pool = 0;
	}
#endif
	if (argc != 1) {
		Usage();
		/* NOTREACHED */
	}
	memset(&cmd_block, 0, sizeof (cmd_block));

	if ((shmid = shmget(SHM_MASTER_KEY, 0, 0)) < 0) {
		fprintf(stderr,
		    catgets(catfd, SET, 2244, "SAM_FS is not running.\n"));
		exit(1);
	}
	if ((memory = shmat(shmid, (void *) NULL, 0444)) == (void *) -1) {
		fprintf(stderr,
		    catgets(catfd, SET, 568,
		    "Cannot attach shared memory segment.\n"));
		exit(1);
	}
	shm_ptr_tbl = (shm_ptr_tbl_t *)memory;
	sprintf(fifo_file, "%s" FIFO_PATH,
	    ((char *)memory + shm_ptr_tbl->fifo_path));

	dev_ptr_tbl =
	    (dev_ptr_tbl_t *)((char *)memory + shm_ptr_tbl->dev_table);
	cmd_block.eq = atoi(*argv);

	if (cmd_block.eq < 0 || cmd_block.eq > dev_ptr_tbl->max_devices) {
		fprintf(stderr,
		    catgets(catfd, SET, 80,
		    "%d is not a valid equipment ordinal.\n"),
		    cmd_block.eq);
		exit(1);
	}
	if (dev_ptr_tbl->d_ent[cmd_block.eq] == 0) {
		fprintf(stderr,
		    catgets(catfd, SET, 80,
		    "%d is not a valid equipment ordinal.\n"),
		    cmd_block.eq);
		exit(1);
	}
开发者ID:BackupTheBerlios,项目名称:samqfs,代码行数:67,代码来源:import.c


示例10: ipc_shmem_init

ssize_t ipc_shmem_init    (ipc_t *ipc, config_t *config){ // {{{
	ssize_t                ret;
	int                    shmid;
	uint32_t               shmkey;
	size_t                 shmsize;
	size_t                 nitems            = NITEMS_DEFAULT;
	size_t                 item_size         = ITEM_SIZE_DEFAULT;
	uintmax_t              f_async           = 0;
	uintmax_t              f_sync            = 0;
	char                  *role_str          = NULL;
	ipc_shmem_userdata    *userdata          = (ipc_shmem_userdata *)ipc->userdata;
	
	userdata->buffer        = HK(buffer);
	userdata->return_result = 1;
	
	hash_data_get(ret, TYPE_UINT32T, shmkey,     config, HK(key));  if(ret != 0) return error("no key supplied");
	hash_data_convert(ret, TYPE_STRINGT, role_str,   config, HK(role)); if(ret != 0) return error("no role supplied");
	hash_data_get(ret, TYPE_SIZET,   item_size,  config, HK(item_size));
	hash_data_get(ret, TYPE_SIZET,   nitems,     config, HK(size));
	hash_data_get(ret, TYPE_UINTT,   f_async,    config, HK(force_async));
	hash_data_get(ret, TYPE_UINTT,   f_sync,     config, HK(force_sync));
	hash_data_get(ret, TYPE_HASHKEYT, userdata->buffer,   config, HK(buffer));
	hash_data_get(ret, TYPE_UINTT,    userdata->return_result, config, HK(return_result));
	
	if( (userdata->role = ipc_string_to_role(role_str)) == ROLE_INVALID)
		return error("invalid role supplied");
	
	free(role_str);
	
	shmsize = nitems * sizeof(ipc_shmem_block) + nitems * item_size + sizeof(ipc_shmem_header); 
	
	if( (shmid = shmget(shmkey, shmsize, IPC_CREAT | 0666)) < 0)
		return error("shmget failed");
	
	if( (userdata->shmaddr = shmat(shmid, NULL, 0)) == (void *)-1)
		return error("shmat failed");
	
	if( (f_async != 0 && f_sync != 0) )
		return error("force_async with force_sync");
	
	userdata->shmblocks = (ipc_shmem_block *)((void *)userdata->shmaddr   + sizeof(ipc_shmem_header));
	userdata->shmdata   = (void *)           ((void *)userdata->shmblocks + nitems * sizeof(ipc_shmem_block));
	userdata->inited    = 1;
	
	userdata->forced_state = FORCE_NONE;
	if(f_async != 0) userdata->forced_state = FORCE_ASYNC;
	if(f_sync  != 0) userdata->forced_state = FORCE_SYNC;
	
	if(userdata->role == ROLE_SERVER){
		userdata->shmaddr->item_size = item_size;
		userdata->shmaddr->nitems    = nitems;
		
		if(shmem_init(userdata) != 0)
			return error("shmem_init failed");
		
		// start threads
		if(pthread_create(&userdata->server_thr, NULL, &ipc_shmem_listen, ipc) != 0)
			return error("pthread_create failed");
	}
	return 0;
} // }}}
开发者ID:shalstvedt,项目名称:frozen,代码行数:61,代码来源:ipc_shmem.c


示例11: main

main() {

        signal(SIGINT,acabou);

        // ligar ao semáforo
        int semid = semget(73452, 1, 0);
        exit_on_error(semid, "semget");

        // ligar à memória partilhada
        int id_mem = shmget(73452, 500 * sizeof(Tcondutor), 0);
        exit_on_error(id_mem, "shmget");
        printf("Ligado à memória\n");

        // Erro do ponteiro
        Tcondutor *p = shmat(id_mem, 0, 0);
        exit_on_null(p, "shmat");

        // input do número do condutor
        char num_aluno[100];
        printf("Número de condutor: ");
        fgets(num_aluno, 100, stdin);
        n = atoi (num_aluno);

        // percorrer a memória partilhada de 500 pos
        // se o número da memória é igual ao inserido
        int i;
        printf("Número inserido: %d\n", n);

        down(semid); // down do semáforo
        for(i = 0; i < 500; i++) {
                if( n == p[i].num_aluno) {
                        p[i].activo = 1; // ativar o condutor
                        printf("Condutor ativo\n");
                        p[i].disponivel_desde = time(NULL); // data atual
                        p[i].PID = getpid(); // o seu PID
  printf("Já és condutor: %s\nA tua matrícula é: %s\n", p[i].nome,p[i].matricula);
                break;
                }
        }
        up(semid); // up do semáforo


        // ligar à fila de mensagens
        int id_msg = msgget(96975, 0);
        exit_on_error(id_msg, "Erro no msgget");
        printf("Ligado à fila\n");

        // ao receber a mensagem 2
        MsgCorrida m;
        while(1) {

                // recebe mensagem 2 do tipo pid
                int status = msgrcv(id_msg, &m, sizeof(m.dados), getpid(), 0);
                exit_on_error(status, "Erro ao receber mensagem 2");
                printf("Mensagem 2 recebida\n");

                // imprimir o pid do passageiro
                printf("O PID do passageiro é: %d\n", m.dados.pid_passageiro);

                // enviar a mensagem 3
                char local[100];
                m.tipo = m.dados.pid_passageiro; // tipo com o PID do passageiro
                m.dados.pid_condutor = getpid(); // PID do condutor com o meu PID
                printf("Meu PID: %d\n", getpid()); // confirmar o meu pid com o Admin e o Passageiro
                printf("Minha localização: ");
                fgets(local, 100, stdin); // minha localização
                local[ strlen(local) - 1 ] = '\0';

                status = msgsnd(id_msg, &m, sizeof(m.dados), 0);
                exit_on_error(status, "Erro ao enviar mensagem 3");
                printf("Mensagem 3 enviada\n");

                // espera de 1-20s
                srand(time(NULL));
                sleep(rand() %20 + 1);

                // pede o valor da corrida
                char val[10];
                printf("Valor da corrida: ");
                fgets(val, 10, stdin);
                val[ strlen(val) - 1 ] = '\0';

                // enviar mensagem 4 com recibo
                m.tipo = 1;
 		m.dados.pid_passageiro = m.dados.pid_passageiro;
                strcpy(m.dados.local_encontro, local);
                m.dados.valor = atof(val);

                status = msgsnd(id_msg, &m, sizeof(m.dados), 0);
                exit_on_error(status, "Erro ao enviar mensagem 4");
                printf("Mensagem 4 enviada\n");
        }

        acabou(SIGINT); // Sinal do Ctrl C
}
开发者ID:GGfpc,项目名称:UBERlinux,代码行数:95,代码来源:UberCondutor.c


示例12: mexFunction

void
mexFunction (int nlhs, mxArray * plhs[], int nrhs, const mxArray * prhs[])
{
  key_t key;
  ACQ_MessagePacketType *packet;
  int msgNumber, msgType, msgId, sampleNumber, numSamples, numChannels, *data;
  int shmid, shmsize;
  int numValues = 28160;

  shmsize = sizeof(ACQ_MessagePacketType) * ACQ_MSGQ_SIZE;

  /* make the key
  if ((key = ftok(ACQ_MSGQ_SHMPATH, ACQ_MSGQ_SHMPROJID)) == -1) {
    perror("ftok");
    exit(1);
    }
   */

  /* use the pre-defined key */
  key = ACQ_MSGQ_SHMKEY;

  /* connect to (and possibly create) the segment */
  if ((shmid = shmget(key, shmsize, 0644 | IPC_CREAT )) == -1)
    mexErrMsgTxt("shmget");

  /* attach to the segment to get a pointer to it */
  packet = shmat(shmid, (void *)0, 0);
  if ((char *)packet == (char *)(-1))
    mexErrMsgTxt("shmat");

  if (nrhs<7)
    mexErrMsgTxt("Not enough input arguments");

  msgNumber    = (int)mxGetScalar(prhs[0])-1; /* one offset in Matlab, zero offset in C */
  /*
  msgType      = (int)mxGetScalar(prhs[1]);
  msgId        = (int)mxGetScalar(prhs[2]);
  sampleNumber = (int)mxGetScalar(prhs[3]);
  numSamples   = (int)mxGetScalar(prhs[4]);
  numChannels  = (int)mxGetScalar(prhs[5]);
  */

  if (mxGetClassID(prhs[6]) != mxINT32_CLASS)
    mexErrMsgTxt("Invalid type of data, should be int32");

  if (msgNumber<0)
    mexErrMsgTxt("Cannot write before the first packet");
  if (msgNumber>=ACQ_MSGQ_SIZE)
    mexErrMsgTxt("Cannot write after the last packet");

  numValues = mxGetNumberOfElements(prhs[6]);
  numValues = ( numValues>28160 ? 28160 : numValues );  /* check boundary */
  numValues = ( numValues<0     ? 0     : numValues );  /* check boundary */

   /* write the meta-information to the packet */
  packet[msgNumber].message_type = (int)mxGetScalar(prhs[1]);
  packet[msgNumber].messageId    = (int)mxGetScalar(prhs[2]);
  packet[msgNumber].sampleNumber = (int)mxGetScalar(prhs[3]);
  packet[msgNumber].numSamples   = (int)mxGetScalar(prhs[4]);
  packet[msgNumber].numChannels  = (int)mxGetScalar(prhs[5]);

   /* write the data to the packet */
  memcpy(packet[msgNumber].data, mxGetData(prhs[6]), numValues*sizeof(int));

  /* detach from the segment */
  if (shmdt(packet) == -1)
    mexErrMsgTxt("shmdt");

} /* end of mexFunction */
开发者ID:Ascronia,项目名称:fieldtrip,代码行数:69,代码来源:write_ctf_shm.c


示例13: try_shm

void try_shm()
{
	key_t key;
	int shmid;
	int child_a, child_b;
	char* shmaddr;
	char* message = "This's message from God";
	struct shmid_ds shminfo;

	get_key('m', &key);

	printf("------------ shared memory------------\n");
	printf("creating shared memory segment with key 0x%x\n", key);
	if((shmid = shmget(key, SHM_SGM_SIZE, DEFAULT_FLAGS)) == -1) {
		perror("shmget");
		exit(1);
	}
	printf("created shared memory segment of id %d\n\n", shmid);

	printf("attaching shared memory address\n");
	if((shmaddr = (char*)shmat(shmid, 0, 0)) == (char*)-1) {
		perror("shmat");
		shmctl(shmid, 0, IPC_RMID, 0);
		exit(1);
	}
	printf("attached shared memory address at 0x%x\n", shmaddr);

	printf("writting message: [%s]\n", message);
	strcpy(shmaddr, message);
	printf("wrote message to shared memory\n\n");

	if((child_a = fork()) == -1) {
		perror("fork");
		shmctl(shmid, 0, IPC_RMID, 0);
		exit(1);
	} else if (!child_a) {
		printf("child_a [%d] in %d\n", getpid(), getppid());
		printf("reading message in child_a[%d]\n", getpid());
		printf("read message: [%s]\n\n", shmaddr);
		
		message = "Hello, this's child_a speaking";

		//print_xsi_info("shm", shmid);

		printf("attaching shared memory address in child_a[%d]\n", getpid());
		if((shmaddr = (char*)shmat(shmid, 0, 0)) == (char*)-1) {
			perror("shmat");
			shmctl(shmid, 0, IPC_RMID, 0);
			exit(1);
		}
		printf("attached shared memory address at 0x%x\n", shmaddr);
		
		strcpy(shmaddr, message);
	
		if((shmid = shmctl(shmid, SHM_STAT, &shminfo)) == -1) {
			perror("shmctl");
			shmctl(shmid, IPC_RMID, 0);
			exit(1);
		}

		printf("current permissions %o\n", shminfo.shm_perm.mode);
		printf("changing permissions\n");
		shminfo.shm_perm.mode = 0664;
		shmctl(shmid, IPC_SET, &shminfo);
		printf("current permissions %o\n\n", shminfo.shm_perm.mode);

		/* child pid retrieved privilege of shmid */
		printf("removing shared memory segment %d\n", shmid);
		if (shmctl(shmid, 0, IPC_RMID ) == -1)
			perror("shmctl, IPC_RMID");
		else 
			printf("removed shared memory segment %d\n\n", shmid);
	} else {
		wait(NULL);
		printf("This's parent process speaking\n");

		printf("read message in parent: [%s]\n\n", shmaddr);

		if ((child_b = fork()) == -1) {
			perror("fork() child_b");
			exit(1);
		} else if (!child_b) {
			printf("child_b [%d] in %d\n", getpid(), getppid());
			printf("shmid already been removed in child_a\n");
		} else {
			wait(NULL);
		}
	}
//	printf("detaching shared memory address\n");
//	if(shmdt(shmaddr) == -1) {
//		perror("shmdt");
//	}
//
//	printf("detached shared memory address\n");

//	printf("removing shared memory segment %d\n", shmid);
//	if (shmctl(shmid, 0, IPC_RMID ) == -1) {
//		perror("shmctl, IPC_RMID");
//	}
//	printf("removed shared memory segment %d\n\n", shmid);
//.........这里部分代码省略.........
开发者ID:Zex,项目名称:walaxsi,代码行数:101,代码来源:walaxsi.c


示例14: Demux


//.........这里部分代码省略.........
    if (w != sys->cur_w || h != sys->cur_h)
    {
        if (sys->es != NULL)
            es_out_Del (demux->out, sys->es);

        /* Update composite pixmap */
        if (sys->window != geo->root)
        {
            xcb_free_pixmap (conn, sys->pixmap); /* no-op first time */
            xcb_composite_name_window_pixmap (conn, sys->window, sys->pixmap);
            xcb_create_pixmap (conn, geo->depth, sys->pixmap,
                               geo->root, geo->width, geo->height);
        }

        sys->es = InitES (demux, w, h, geo->depth, &sys->bpp);
        if (sys->es != NULL)
        {
            sys->cur_w = w;
            sys->cur_h = h;
            sys->bpp /= 8; /* bits -> bytes */
        }
    }

    /* Capture screen */
    xcb_drawable_t drawable =
        (sys->window != geo->root) ? sys->pixmap : sys->window;
    free (geo);

    block_t *block = NULL;
#if HAVE_SYS_SHM_H
    if (sys->shm)
    {   /* Capture screen through shared memory */
        size_t size = w * h * sys->bpp;
        int id = shmget (IPC_PRIVATE, size, IPC_CREAT | 0777);
        if (id == -1) /* XXX: fallback */
        {
            msg_Err (demux, "shared memory allocation error: %m");
            goto noshm;
        }

        /* Attach the segment to X and capture */
        xcb_shm_get_image_reply_t *img;
        xcb_shm_get_image_cookie_t ck;

        xcb_shm_attach (conn, sys->segment, id, 0 /* read/write */);
        ck = xcb_shm_get_image (conn, drawable, x, y, w, h, ~0,
                                XCB_IMAGE_FORMAT_Z_PIXMAP, sys->segment, 0);
        xcb_shm_detach (conn, sys->segment);
        img = xcb_shm_get_image_reply (conn, ck, NULL);
        xcb_flush (conn); /* ensure eventual detach */

        if (img == NULL)
        {
            shmctl (id, IPC_RMID, 0);
            goto noshm;
        }
        free (img);

        /* Attach the segment to VLC */
        void *shm = shmat (id, NULL, 0 /* read/write */);
        shmctl (id, IPC_RMID, 0);
        if (-1 == (intptr_t)shm)
        {
            msg_Err (demux, "shared memory attachment error: %m");
            return;
        }
开发者ID:Aki-Liang,项目名称:vlc-2.1.0.oldlib-2010,代码行数:67,代码来源:xcb.c


示例15: createSharedMemory

int createSharedMemory() {
	key_t key = ftok("producer", 'x');

	return shmget(key, bufferSize(BUFFERSIZE), IPC_CREAT | 0666);
}
开发者ID:Cortys,项目名称:KMS,代码行数:5,代码来源:producer.c


示例16: vj_calloc

//@ new producer, puts frame in shm
void	*vj_shm_new_master( const char *homedir, VJFrame *frame)
{
	vj_shm_t *v = (vj_shm_t*) vj_calloc(sizeof(vj_shm_t));
	v->parent   = 1;

	if( vj_shm_file_ref( v, homedir ) == -1 ) {
		free(v);
		return NULL;
	}

	long size = (frame->width * frame->height * 4);

	//@ create
	v->shm_id = shmget( v->key,size, IPC_CREAT |0666 );

	if( v->shm_id == -1 ) {
		veejay_msg(0,"Error while allocating shared memory segment: %s", strerror(errno));
		failed_init_cleanup( v );
		return NULL;
	}

	//@ attach
	v->sms 	    =  shmat( v->shm_id, NULL , 0 );
	if( v->sms == NULL || v->sms == (char*) (-1) ) {
		shmctl( v->shm_id, IPC_RMID, NULL );
		veejay_msg(0, "Failed to attach to shared memory:%s",strerror(errno));
		failed_init_cleanup(v);
		return NULL;
	}

	pthread_rwlockattr_t	rw_lock_attr;
	veejay_memset( v->sms, 0, size );

	uint8_t *Y = v->sms + HEADER_LENGTH;
	uint8_t *U = Y + (frame->width * frame->height);
	uint8_t *V = U + ( (frame->width * frame->height)/2);
	
	veejay_memset( U, 128, frame->uv_len);
	veejay_memset( V, 128, frame->uv_len);

	//@ set up frame info (fixme, incomplete)
//	vj_shared_data *data = (vj_shared_data*) &(v->sms[0]);

	vj_shared_data *data = (vj_shared_data*) v->sms;
	data->resource_id    = v->shm_id;
	data->header[0]      = frame->width;
	data->header[1]      = frame->height;
	data->header[2]      = frame->stride[0];
	data->header[3]      = frame->stride[1];
	data->header[4]      = frame->stride[2];
	data->header[5]      = 513; // format LIVIDO_PALETTE_YUV422P 

	veejay_msg(VEEJAY_MSG_INFO, "Shared Resource:  Starting address: %p", data );
	veejay_msg(VEEJAY_MSG_INFO, "Shared Resource:  Frame data      : %p", data + HEADER_LENGTH );
	veejay_msg(VEEJAY_MSG_INFO, "Shared Resource:  Static resolution of %d x %d, YUV 4:2:2 planar",
			data->header[0],data->header[1] );
	veejay_msg(VEEJAY_MSG_DEBUG,"Shared Resource:  Planes {%d,%d,%d} format %d",
			data->header[2],data->header[3],data->header[4],data->header[5]);

	int	res	= pthread_rwlockattr_init( &rw_lock_attr );
	if( res == -1 ) {
		veejay_msg(0, "Failed to create rw lock: %s",strerror(errno));
		shmctl( v->shm_id, IPC_RMID, NULL );
		free(v);
		return NULL;
	}

	res	    = pthread_rwlockattr_setpshared( &rw_lock_attr, PTHREAD_PROCESS_SHARED );
	if( res == -1 ) {
		veejay_msg(0, "Failed to set PTHREAD_PROCESS_SHARED: %s",strerror(errno));
		shmctl( v->shm_id, IPC_RMID, NULL );
		free(v);
		return NULL;
	}

	res	    = pthread_rwlock_init( &data->rwlock, &rw_lock_attr );
	if( res == -1 ) {
		shmctl(v->shm_id, IPC_RMID , NULL );
		veejay_msg(0, "Failed to initialize rw lock:%s",strerror(errno));
		free(v);
		return NULL;
	}

	veejay_msg( VEEJAY_MSG_INFO, "Shared Memory ID = %d", v->shm_id );
	veejay_msg( VEEJAY_MSG_INFO, "Your Shared Memory Key = %d   <---- ", v->key );
	veejay_msg( VEEJAY_MSG_INFO, "Starting Address: %p, Frame starts at: %p, Lock at %p",
			v->sms, v->sms + HEADER_LENGTH, &(data->rwlock));


	simply_my_shmid = v->key;
	simply_my_shmkey = v->shm_id;


	return v;
}
开发者ID:d-j-a-y,项目名称:veejay-dyne-outdated,代码行数:96,代码来源:vj-shm.c


示例17: invopen

int
invopen(INVCONTROL *invcntl, char *invname, char *invpost, int stat)
{
	int	read_index;

	if ((invcntl->invfile = vpfopen(invname, ((stat == 0) ? "rb" : "r+b"))) == NULL) {
		/* If db created without '-f', but now invoked with '-f cscope.out',
		 * we need to check for 'cscope.in.out', rather than 'cscope.out.in': 
		 * I.e, hack around our own violation of the inverse db naming convention */
		if (!invflipname(invname, INVNAME2, INVNAME)) {
			if ((invcntl->invfile = vpfopen(invname, ((stat == 0) ? "rb" : "r+b")))) 
				goto openedinvname;
			invflipname(invname, INVNAME, INVNAME2); /* change back for err msg */
		} 
		/* more silliness: if you create the db with '-f cscope', then try to open 
		 * it without '-f cscope', you'll fail unless we check for 'cscope.out.in'
		 * here. */
		else if (!invflipname(invname, INVNAME, INVNAME2)) {
			if ((invcntl->invfile = vpfopen(invname, ((stat == 0) ? "rb" : "r+b")))) 
				goto openedinvname;
			invflipname(invname, INVNAME2, INVNAME); /* change back for err msg */
		}	
		invcannotopen(invname);
		return(-1);
	}
openedinvname:
	if (fread(&invcntl->param, sizeof(invcntl->param), 1, invcntl->invfile) == 0) {
		fprintf(stderr, "%s: empty inverted file\n", argv0);
		goto closeinv;
	}
	if (invcntl->param.version != FMTVERSION) {
		fprintf(stderr, "%s: cannot read old index format; use -U option to force database to rebuild\n", argv0);
		goto closeinv;
	}
	assert(invcntl->param.sizeblk == sizeof(t_logicalblk));

	if (stat == 0 && invcntl->param.filestat == INVALONE) {
		fprintf(stderr, "%s: inverted file is locked\n", argv0);
		goto closeinv;
	}
	if ((invcntl->postfile = vpfopen(invpost, ((stat == 0) ? "rb" : "r+b"))) == NULL) {
		/* exact same naming convention hacks as above for invname */
		if (!invflipname(invpost, INVPOST2, INVPOST)) {
			if ((invcntl->postfile = vpfopen(invpost,  

鲜花

握手

雷人

路过

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

请发表评论

全部评论

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

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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