Beispiel #1
0
/*
 * 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

    }
  }
}
Beispiel #2
0
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();
}
Beispiel #3
0
int main(int argc, char *argv[])
{
#ifdef _WIN32
    DWORD numRead;
    DWORD numToWrite;

    if (argc != 2)
    {
        HANDLE namedPipe = CreateNamedPipe(TEXT("\\\\.\\pipe\\Pipe"),
            PIPE_ACCESS_DUPLEX,
            PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
            PIPE_UNLIMITED_INSTANCES,
            1024, 1024,
            NMPWAIT_USE_DEFAULT_WAIT,
            NULL);

        if (namedPipe == INVALID_HANDLE_VALUE)
        {
            cout << "Can't create pipe. Error. Press any key to exit " << GetLastError();
            _getch();
            exit(0);
        }

        HANDLE serverSemaphore = CreateSemaphore(NULL, 0, 1, TEXT("serverSemaphore"));
        HANDLE clientSemaphore = CreateSemaphore(NULL, 0, 1, TEXT("clientSemaphore"));

        MyProcess *clientProcess = new MyProcess(argv[0]);

        ConnectNamedPipe(namedPipe, NULL);

        WaitForSingleObject(serverSemaphore, INFINITE);

        char *buffer = NULL;
        buffer = (char *)malloc(sizeof(char) * 1024);

        printf("Server process\n");

        if (!WriteFile(namedPipe, "Ready", 1024, &numToWrite, NULL))
            return 0;

        while (1)
        {
            ReleaseSemaphore(clientSemaphore, 1, NULL);
            WaitForSingleObject(serverSemaphore, INFINITE);

            if (ReadFile(namedPipe, buffer, 1024, &numRead, NULL))
                printf("Client message: %s", buffer);

            if (!strcmp(buffer, "exit"))
            {
                CloseHandle(namedPipe);
                CloseHandle(serverSemaphore);
                free(buffer);
                return 0;
            }

            printf("\nInput message to client: ");
            fflush(stdin);
            gets_s(buffer, 1024);

            if (!WriteFile(namedPipe, buffer, 1024, &numToWrite, NULL))
                break;

            ReleaseSemaphore(clientSemaphore, 1, NULL);

            if (!strcmp(buffer, "exit"))
            {
                CloseHandle(namedPipe);
                CloseHandle(serverSemaphore);

                free(buffer);
                return 0;
            }
        }
        return 0;
    }
    else
    {
        HANDLE serverSemaphore = OpenSemaphore(EVENT_ALL_ACCESS, FALSE, TEXT("serverSemaphore"));
        HANDLE clientSemaphore = OpenSemaphore(EVENT_ALL_ACCESS, FALSE, TEXT("clientSemaphore"));

        HANDLE namedPipe = CreateFile(TEXT("\\\\.\\pipe\\Pipe"),
            GENERIC_READ | GENERIC_WRITE,
            0,
            NULL,
            OPEN_EXISTING,
            0,
            NULL);

        if (namedPipe == INVALID_HANDLE_VALUE)
        {
            printf("Can't create pipe. Error. Press any key to exit", GetLastError());
            _getch();
            exit(0);
        }

        ReleaseSemaphore(serverSemaphore, 1, NULL);

        char *buffer = NULL;
        buffer = (char *)malloc(sizeof(char) * 1024);

        printf("Client process\n");

        while (1)
        {
            WaitForSingleObject(clientSemaphore, INFINITE);

            if (ReadFile(namedPipe, buffer, 1024, &numRead, NULL))
            {
                if (!strcmp(buffer, "exit"))
                {
                    CloseHandle(clientSemaphore);
                    free(buffer);
                    return 0;
                }

                printf("Server message: %s", buffer);

                char input[1024] = { '\0' };
                cout << "\nInput message to server: ";
                fflush(stdin);
                gets_s(input, 1024);

                if (!WriteFile(namedPipe, input, 1024, &numToWrite, NULL))
                    break;

                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)
Beispiel #4
0
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
        for (i = 0; i < n_clients; i++) {
	    unsigned tid;

	    pids[i] = (HANDLE) _beginthreadex(NULL, 0, runClientThread,
					      NULL, 0, &tid);
	}
	for (i = 0; i < n_clients; i++) {
	    WaitForSingleObject(pids[i], INFINITE);
	    CloseHandle(pids[i]);
	}
#else
        for (i = 0; i < n_clients; i++) {
	    pid_t child = fork();
	    int rc;

	    switch (child) {
	    case 0:
	        rc = runClientThread(NULL);
		exit(rc);
	    default:
	        pids[i] = child;
	    }
	}
	for (i = 0; i < n_clients; i++) {
	    int status;

	    waitpid(pids[i], &status, 0);
	}
#endif
    }
    reportDone();

    transactions = 1;
#ifdef _WIN32
    start_time = GetTickCount();
#else
    gettimeofday(&start_time, NULL);
#endif
    if (n_clients < 2) {
        runClientThread(NULL);
    } else {
#ifdef _WIN32
        for (i = 0; i < n_clients; i++) {
	    unsigned tid;

	    pids[i] = (HANDLE) _beginthreadex(NULL, 0,runClientThread,
					      NULL, 0, &tid);
	}
	for (i = 0; i < n_clients; i++) {
	    WaitForSingleObject(pids[i], INFINITE);
	    CloseHandle(pids[i]);
	}
#else
        for (i = 0; i < n_clients; i++) {
	    pid_t child = fork();
	    int rc;

	    switch (child) {
	    case 0:
	        rc = runClientThread(NULL);
		exit(rc);
	    default:
	        pids[i] = child;
	    }
	}
	for (i = 0; i < n_clients; i++) {
	    int status;

	    waitpid(pids[i], &status, 0);
	}
#endif
    }
    reportDone();

    fprintf(stdout, "--------------------\n");
    fprintf(stdout, "Error counters, consult source for stat_counts[].\n");
    for (i = 0; i < 16; i++) {
	if (i == 0) {
	    fprintf(stdout, "stat_counts[0..7]: ");
	}
        fprintf(stdout, " %d", stat_counts[i]);
	if (i == 7) {
	    fprintf(stdout, "\nstat_counts[8..15]:");
	}
    }
    fprintf(stdout, "\n\n");
    return 0;
}
Beispiel #5
0
/* ////////////////////////////////////////////////////////////////////////// */
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;
}
Beispiel #6
0
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)
                    {
                        // Fils - Simulateur
                        Simulateur();
                    }
                    else
                    {
                        // Père
                        /* --- Moteur --- */
                        waitpid(tachesPid[--taches], NULL, 0);

                        /* --- Destruction --- */
                        while (taches)
                        {
                            kill(tachesPid[--taches], SIGUSR2);
                        }
                        semctl(semId, 0, IPC_RMID, NULL);
                        shmctl(shmId, IPC_RMID, NULL);
                        for (size_t i = 0; i < NB_BARRIERES; i++)
                        {
                            msgctl(filesId[i], IPC_RMID, NULL);
                        }
                        TerminerApplication(true);
                        exit(0);
                    }
                }
            }
        }
    }

    return 0;
}
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)
            {
                //perror("recvfrom()");
                exit(6);
            }
            
            
            //printf("recebi\n");
            
            if(bufferer[19] == '0'){
                buf.isDoor = false;
            }else{
                buf.isDoor = true;
            }
            
            if(bufferer[31] == '0'){
                buf.isPresent = false;
            }else{
                buf.isPresent = true;
            }
            
            
            for(int i = 0;i < 8;i++){
                
                buf.ra[i] = bufferer[3 + i];
                
            }
            
            
            
            
            //identificacao de alguem que passou na porta
            if(buf.isDoor){
                // printf("contando");
                data->doorCounter++;
                
            }else{
                //requisicao do aplicativo,inicialmente checa se o RA ja se encontra no sistema
                
                if(buf.isPresent){
                    
                    //printf("aluno");
                    
                    int flag = 0;
                    
                    for (int i = 0; i < data->count; i++) {
                        
                        char temp[9];
                        strcpy(temp, buf.ra);
                        temp[8] = '\0';
                        
                        //igual
                        if(strcmp(data->alunosRA[i], buf.ra) == 0){
                            flag++;
                            // printf("repetido");
                            
                            //enviar mensagem falando que nao foi aceitado
                            char resp[22];
                            resp[0] = 'R';
                            resp[1] = 'A';
                            resp[2] = ':';
                            resp[3] = temp[0];
                            resp[4] = temp[1];
                            resp[5] = temp[2];
                            resp[6] = temp[3];
                            resp[7] = temp[4];
                            resp[8] = temp[5];
                            resp[9] = temp[6];
                            resp[10] = temp[7];
                            resp[11] = ',';
                            resp[12] = 'r';
                            resp[13] = 'e';
                            resp[14] = 'c';
                            resp[15] = 'e';
                            resp[16] = 'b';
                            resp[17] = 'e';
                            resp[18] = 'u';
                            resp[19] = ':';
                            resp[20] = '1';
                            resp[21] = '\0';

                            
                            if (send(ns, resp, strlen(resp)+1, 0) < 0)
                            {
                                perror("Send()");
                                exit(7);
                            }
                            
                            
                            
                        }
                        
                    }
                    
                    if(!flag){
                        strcpy(data->alunosRA[data->count], buf.ra);
                        data->alunosRA[data->count][8] = '\0';
                        data->count++;
                        
                        //enviar mensagem falando que foi aceitado
                        
                        char resp[22];
                        resp[0] = 'R';
                        resp[1] = 'A';
                        resp[2] = ':';
                        resp[3] = buf.ra[0];
                        resp[4] = buf.ra[1];
                        resp[5] = buf.ra[2];
                        resp[6] = buf.ra[3];
                        resp[7] = buf.ra[4];
                        resp[8] = buf.ra[5];
                        resp[9] = buf.ra[6];
                        resp[10] = buf.ra[7];
                        resp[11] = ',';
                        resp[12] = 'r';
                        resp[13] = 'e';
                        resp[14] = 'c';
                        resp[15] = 'e';
                        resp[16] = 'b';
                        resp[17] = 'e';
                        resp[18] = 'u';
                        resp[19] = ':';
                        resp[20] = '1';
                        resp[21] = '\0';
                        
                        //comentado aguardando cliente receber
                        /*
                        if (send(ns, resp, strlen(resp)+1, 0) < 0)
                        {
                            perror("Send()");
                            exit(7);
                        }
                        
                        */
                        
                        
                        
                        
                    }
                }
                
            }
            fflush(stdout);
            
            printf("\n\n----------\n\n");
            printf("entraram %d pessoas\n----------\nRAs cadastrados:\n",data->doorCounter);
            
            for (int i  = 0; i < data->count; i++) {
                printf("%s\n",data->alunosRA[i]);
                
            }
            
            

            
            
            
            
            
            /* Fecha o socket conectado ao cliente */
            close(ns);
            
            /* Processo filho termina sua execuÁ„o */
            //printf("[%d] Processo filho terminado com sucesso.\n", fid);
            exit(0);
        }
        else
        {
            
            
            
            /*
             * Processo pai 
             */
            if (pid > 0)
            {
                //printf("Processo filho criado: %d\n", pid);
                
                /* Fecha o socket conectado ao cliente */
                close(ns);
                while (waitpid(0,NULL,WNOHANG)!=-1); // clean system tables non blocking

            }
            else
            {
                close (ns);
                while (waitpid(0,NULL,WNOHANG)!=-1); // clean system tables non blocking
                //perror("Fork()");
                //exit(7);
            }
        }
        
        
        
        
        
        
       
    
    }
  
    
}
Beispiel #8
0
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;
}
Beispiel #9
0
int
main(int argc, char **argv)
{
	int	shmid, fifo_fd;
	int	audit_eod = 0, strange = 0, media = 0;
	void	*memory;
	char	fifo_file[MAXPATHLEN];
	char	*volser = NULL, *barcode = NULL;

	dev_ent_t	*device;
	dev_ptr_tbl_t	*dev_ptr_tbl;
	shm_ptr_tbl_t	*shm_ptr_tbl;
	sam_cmd_fifo_t	cmd_block;

	int	pool_count = -1, l_opt = 0;
	void   *api_handle;
	POOL    what_pool = -1;

#if !defined(_NoSTK_)
	ACS_STAT(dl_acs_status);
	ACS_QP(dl_acs_query_pool);
	ACS_QS(dl_acs_query_scratch);
	ACS_RSP(dl_acs_response);
	ACS_SA(dl_acs_set_access);
	ACS_SS(dl_acs_set_scratch);
#endif

	CustmsgInit(0, NULL);

	program_name = (char *)basename(argv[0]);

#if !defined(DEBUG)
	if (geteuid() != 0) {
		fprintf(stderr, catgets(catfd, SET, 100,
		    "%s may be run only by super-user.\n"),
		    program_name);
		exit(1);
	}
#endif
	argc--;
	argv++;
	if (argc <= 0) {
		Usage();
		/* NOTREACHED */
	}
	while (argc > 1) {
		if (strcmp(*argv, "-v") == 0) {
			argc--;
			argv++;
			if (argc < 2) {
				Usage();
				/* NOTREACHED */
			}
			volser = strdup(*argv);
			argc--;
			argv++;
		} else if (strcmp(*argv, "-b") == 0) {
			argc--;
			argv++;
			if (argc < 2) {
				Usage();
				/* NOTREACHED */
			}
			barcode = strdup(*argv);
			argc--;
			argv++;
		} else if (strcmp(*argv, "-m") == 0) {
			argc--;
			argv++;
			if (argc < 2) {
				Usage();
				/* NOTREACHED */
			}
			if ((media = media_to_device(*argv)) == -1) {
				fprintf(stderr,
				    catgets(catfd, SET, 2755,
				    "Unknown media type %s.\n"), *argv);
				exit(1);
			}
			argc--;
			argv++;
		} else if (strcmp(*argv, "-e") == 0) {
			argc--;
			argv++;
			audit_eod = TRUE;
		} else if ((strcmp(*argv, "-n") == 0) ||
		    (strcmp(*argv, "-N") == 0)) {
			argc--;
			argv++;
			strange = TRUE;
		} else if (strcmp(*argv, "-s") == 0) {
			argc--;
			argv++;
			if (argc < 2) {
				Usage();
				/* NOTREACHED */
			}
			what_pool = atoi(*argv);
			if (what_pool < 0) {
				Usage();
				/* NOTREACHED */
			}
			argc--;
			argv++;
		} else if (strcmp(*argv, "-c") == 0) {
			argc--;
			argv++;
			if (argc < 2) {
				Usage();
				/* NOTREACHED */
			}
			pool_count = atoi(*argv);
			if (pool_count < 0) {
				Usage();
				/* NOTREACHED */
			}
			argc--;
			argv++;
		} else if (strcmp(*argv, "-l") == 0) {
			l_opt = 1;
			argc--;
			argv++;
		} else {
			fprintf(stderr,
			    catgets(catfd, SET, 2760,
			    "Unknown option %s.\n"),
			    *argv);
			Usage();
			/* NOTREACHED */
		}
	}

	if (volser && (what_pool > 0 || pool_count > 0)) {
		fprintf(stderr,
		    catgets(catfd, SET, 2255,
		    "Scratch pools and specifying vsn are "
		    "mutually exclusive.\n"));
		Usage();
		/* NOTREACHED */
	}
	if (l_opt && (pool_count == 0 || what_pool < 0)) {
		fprintf(stderr, catgets(catfd, SET, 13215,
		    "%s: -l option only allowed if importing by pools.\n"),
		    program_name);
		Usage();
		/* NOTREACHED */
	}
	if (audit_eod && strange) {
		fprintf(stderr,
		    catgets(catfd, SET, 13205,
		    "%s: -e and -n are mutually exclusive.\n"),
		    program_name);
		exit(1);
	}
#if !defined(_NoSTK_)
	if (what_pool >= 0 || pool_count > 0) {
		if ((api_handle =
		    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);
	}
	device =
	    (dev_ent_t *)((char *)memory +
	    (int)dev_ptr_tbl->d_ent[cmd_block.eq]);

	if (device->equ_type != DT_HISTORIAN && !device->status.b.ready) {
		fprintf(stderr,
		    catgets(catfd, SET, 853, "Device %d is not ready.\n"),
		    cmd_block.eq);
		exit(1);
	}
	if (!IS_ROBOT(device)) {
		fprintf(stderr,
		    catgets(catfd, SET, 79,
		    "%d is not a robotic device.\n"),
		    cmd_block.eq);
		exit(1);
	}
	if (device->equ_type != DT_HISTORIAN && barcode != NULL) {
		fprintf(stderr,
		    catgets(catfd, SET, 517,
		    "barcode may only be specified for the historian.\n"));
		exit(1);
	}
	if (!strange && (device->equ_type != DT_HISTORIAN && media != 0)) {
		fprintf(stderr,
		    catgets(catfd, SET, 1643,
		"media type may only be specified for the historian.\n"));
		exit(1);
	}
	if (device->equ_type == DT_HISTORIAN && audit_eod) {
		fprintf(stderr,
		    catgets(catfd, SET, 487,
		    "audit_eod (-e) is not allowed for the historian.\n"));
		exit(1);
	}
	cmd_block.magic = CMD_FIFO_MAGIC;
	cmd_block.slot = ROBOT_NO_SLOT;
	cmd_block.part = 0;
	if (device->equ_type == DT_HISTORIAN) {
		if (media == 0) {
			fprintf(stderr,
			    catgets(catfd, SET, 1645,
			"media type must be supplied for the historian.\n"));
			exit(1);
		}
		cmd_block.cmd = CMD_FIFO_ADD_VSN;
		cmd_block.media = media;
		if (volser != NULL)
			strncpy(cmd_block.vsn, volser, sizeof (vsn_t));
		if (barcode != NULL) {
			cmd_block.flags |= ADDCAT_BARCODE;
			memccpy(cmd_block.info, barcode, '\0', 127);
		}
		if (volser == NULL && barcode == NULL) {
			fprintf(stderr,
			    catgets(catfd, SET, 2873,
			    "VSN and/or barcode must be supplied for "
			    "import into the historian.\n"));
			exit(1);
		}
	} else if (volser == NULL && what_pool < 0) {
		if (device->type == DT_GRAUACI || device->type == DT_STKAPI ||
		    device->type == DT_IBMATL || device->type == DT_SONYPSC) {
			fprintf(stderr,
			    catgets(catfd, SET, 1328,
			    "Import to GRAU, STK, SONY and IBM libraries "
			    "must be by vsn or scratch pool(STK only).\n"));
			exit(1);
		}
		cmd_block.cmd = CMD_FIFO_IMPORT;
		if (audit_eod)
			cmd_block.flags |= CMD_IMPORT_AUDIT;

		if (strange)
			cmd_block.flags |= CMD_IMPORT_STRANGE;
	}
#if !defined(_NoSTK_)
           else if (what_pool >= 0) {
		int		err;
		void	   *buffer, *buffer2;
		POOL	    pools[MAX_ID];
		SEQ_NO	  sequence = 0, resp_seq;
		REQ_ID	  resp_req;
		VOLRANGE	vol_ids[MAX_ID];
		ACS_RESPONSE_TYPE type;
		ACS_QUERY_POL_RESPONSE *qp_resp;
		QU_POL_STATUS  *qp_status;

		if (device->type != DT_STKAPI) {
			fprintf(stderr,
			    catgets(catfd, SET, 2254,
			    "Scratch pool only supported on STK.\n"));
			exit(1);
		}
		if ((buffer = (void *) malloc(4096)) == NULL ||
		    (buffer2 = (void *) malloc(4096)) == NULL) {
			fprintf(stderr,
			    catgets(catfd, SET, 1606,
			    "malloc: %s\n"), strerror(errno));
			exit(1);
		}
		/*
		 * Set the environment variable for the port
		 * number sam-stkd is using to talk to ACSLS.
		 */
		if (device->dt.rb.port_num == 0) {
			sprintf(env_acs_portnum, "%s=%d",
			    ACS_PORTNUM, ACS_DEF_PORTNUM);
		} else {
			sprintf(env_acs_portnum, "%s=%d",
			    ACS_PORTNUM, device->dt.rb.port_num);
		}

		putenv(env_acs_portnum);

		if (device->vsn[0] != '\0')	/* if access set */
			dl_acs_set_access(&device->vsn[0]);

		pools[0] = what_pool;
		if ((err = dl_acs_query_pool(sequence, pools, 1))) {
			fprintf(stderr,
			    catgets(catfd, SET, 339,
			    "acs_query_pool failed: %s\n"),
			    dl_acs_status(err));
			exit(1);
		}
		do {
			if ((err = dl_acs_response(-1, &resp_seq,
			    &resp_req, &type, buffer)) != STATUS_SUCCESS) {
				fprintf(stderr,
				    catgets(catfd, SET, 353,
				    "acs_response:failure %s\n"),
				    dl_acs_status(err));
				exit(1);
			}
			if (resp_seq != sequence) {
				fprintf(stderr,
				    catgets(catfd, SET, 352,
				    "acs_response: wrong sequence.\n"));
				exit(1);
			}
		} while (type != RT_FINAL);

		qp_resp = (ACS_QUERY_POL_RESPONSE *) buffer;
		if (qp_resp->query_pol_status != STATUS_SUCCESS) {
			fprintf(stderr,
			    catgets(catfd, SET, 341,
			    "acs_query_pool: status error: %s\n"),
			    dl_acs_status(qp_resp->query_pol_status));
			exit(1);
		}
		if (qp_resp->count != 1) {
			fprintf(stderr,
			    catgets(catfd, SET, 340,
			    "acs_query_pool: count error: %d.\n"),
			    qp_resp->count);
			exit(1);
		}
		qp_status = &qp_resp->pool_status[0];
		if (qp_status->pool_id.pool != what_pool) {
			fprintf(stderr,
			    catgets(catfd, SET, 342,
			    "acs_query_pool: wrong pool %d.\n"),
			    qp_status->pool_id.pool);
			exit(1);
		}
		if (qp_status->volume_count < pool_count) {
			fprintf(stderr,
			    catgets(catfd, SET, 2910,
			    "Warning: Only %d volumes left in pool.\n"),
			    qp_status->volume_count);
			pool_count = qp_status->volume_count;
		}
		while (pool_count > 0) {
			int		ii, jj;
			QU_SCR_STATUS  *qs_status;
			ACS_QUERY_SCR_RESPONSE *qs_resp;
			ACS_SET_SCRATCH_RESPONSE *ss_resp;

			sequence++;
			if ((err = dl_acs_query_scratch(sequence, pools, 1))) {
				fprintf(stderr,
				    catgets(catfd, SET, 343,
				    "acs_query_scratch failed: %s\n"),
				    dl_acs_status(err));
				exit(1);
			}
			do {
				if ((err = dl_acs_response(-1, &resp_seq,
				    &resp_req, &type, buffer)) !=
				    STATUS_SUCCESS) {
					fprintf(stderr,
					    catgets(catfd, SET, 349,
					    "acs_response(qu_scr):failure "
					    "%s\n"), dl_acs_status(err));
					exit(1);
				}
				if (resp_seq != sequence) {
					fprintf(stderr,
					    catgets(catfd, SET, 348,
					    "acs_response(qu_scr): "
					    "wrong sequence.\n"));
					exit(1);
				}
			} while (type != RT_FINAL);

			qs_resp = (ACS_QUERY_SCR_RESPONSE *) buffer;
			if (qs_resp->count == 0) {
				fprintf(stderr,
				    catgets(catfd, SET, 344,
				    "acs_query_scratch: "
				    "No scratch volumes.\n"));
				exit(1);
			}
			if ((fifo_fd = open(fifo_file, O_WRONLY)) < 0) {
				perror(catgets(catfd, SET, 1113,
				    "Unable to open command fifo:"));
				exit(1);
			}
			for (ii = 0, jj = (int)qs_resp->count;
			    ii < jj && pool_count > 0;
			    ii++) {
			/* N.B. Bad indentation to meet cstyle requirements */
			qs_status = &qs_resp->scr_status[ii];
			if (qs_status->status != STATUS_VOLUME_HOME) {
				fprintf(stderr,
				    catgets(catfd, SET, 2349,
				    "Skipping %s: not home\n"),
				    qs_status->vol_id);
				continue;
			}
			sequence++;
			memset(&vol_ids[0].endvol.external_label[0],
			    0, sizeof (VOLID));
			memset(&vol_ids[0].startvol.external_label[0],
			    0, sizeof (VOLID));
			strncpy(&vol_ids[0].startvol.external_label[0],
			    qs_status->vol_id.external_label,
			    sizeof (VOLID));
			strncpy(&vol_ids[0].endvol.external_label[0],
			    qs_status->vol_id.external_label,
			    sizeof (VOLID));
			if ((err = dl_acs_set_scratch(sequence, NO_LOCK_ID,
			    what_pool, vol_ids, FALSE, 1))) {
				fprintf(stderr,
				    catgets(catfd, SET, 354,
				    "acs_set_scratch failed: %s\n"),
				    dl_acs_status(err));
				exit(1);
			}
			do {
				if ((err = dl_acs_response(
				    -1, &resp_seq, &resp_req, &type,
				    buffer2)) != STATUS_SUCCESS) {
					fprintf(stderr,
					    catgets(catfd, SET, 351,
					    "acs_response(set_scr):"
					    "failure %s\n"),
					    dl_acs_status(err));
					exit(1);
				}
				if (resp_seq != sequence) {
					fprintf(stderr,
					    catgets(catfd, SET, 350,
					    "acs_response(set_scr): "
					    "wrong sequence.\n"));
					exit(1);
				}
			} while (type != RT_FINAL);

			ss_resp = (ACS_SET_SCRATCH_RESPONSE *) buffer2;
			if (ss_resp->set_scratch_status == STATUS_SUCCESS ||
			    ss_resp->set_scratch_status ==
			    STATUS_POOL_LOW_WATER) {
				if (ss_resp->vol_status[0] == STATUS_SUCCESS) {
					strncpy(cmd_block.vsn, ss_resp->
					    vol_id[0].external_label,
					    sizeof (vsn_t));
					cmd_block.cmd = CMD_FIFO_ADD_VSN;
					if (l_opt)
						fprintf(stdout, "%s\n",
						    cmd_block.vsn);
					write(fifo_fd, &cmd_block,
					    sizeof (sam_cmd_fifo_t));
					pool_count--;
				}
			} else {
				if (ss_resp->set_scratch_status !=
				    STATUS_VOLUME_ACCESS_DENIED) {
						fprintf(stderr,
						    "acs_set_scratch: %s.\n",
						    dl_acs_status(ss_resp->
						    set_scratch_status));
						exit(1);
					}
				}
			} /* end for */
			close(fifo_fd);
			if (pool_count == 0)
				exit(0);
		}
	}
#endif
        else {
		strncpy(cmd_block.vsn, volser, sizeof (vsn_t));
		if (audit_eod)
			cmd_block.flags |= CMD_ADD_VSN_AUDIT;

		if (strange)
			cmd_block.flags |= CMD_ADD_VSN_STRANGE;

		cmd_block.cmd = CMD_FIFO_ADD_VSN;
	}

	if ((fifo_fd = open(fifo_file, O_WRONLY)) < 0) {
		perror(catgets(catfd, SET, 1113,
		    "Unable to open command fifo:"));
		exit(1);
	}
	write(fifo_fd, &cmd_block, sizeof (sam_cmd_fifo_t));

	close(fifo_fd);
	return (0);
}
Beispiel #10
0
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;
} // }}}
Beispiel #11
0
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
}
Beispiel #12
0
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 */
Beispiel #13
0
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);
}
Beispiel #14
0
/**
 * Processing callback
 */
static void Demux (void *opaque)
{
    demux_t *demux = opaque;
    demux_sys_t *sys = demux->p_sys;
    xcb_connection_t *conn = sys->conn;

    /* Determine capture region */
    xcb_get_geometry_cookie_t gc;
    xcb_query_pointer_cookie_t qc;

    gc = xcb_get_geometry (conn, sys->window);
    if (sys->follow_mouse)
        qc = xcb_query_pointer (conn, sys->window);

    xcb_get_geometry_reply_t *geo = xcb_get_geometry_reply (conn, gc, NULL);
    if (geo == NULL)
    {
        msg_Err (demux, "bad X11 drawable 0x%08"PRIx32, sys->window);
discard:
        if (sys->follow_mouse)
            xcb_discard_reply (conn, gc.sequence);
        return;
    }

    int w = sys->w;
    int h = sys->h;
    int x, y;

    if (sys->follow_mouse)
    {
        xcb_query_pointer_reply_t *ptr =
            xcb_query_pointer_reply (conn, qc, NULL);
        if (ptr == NULL)
        {
            free (geo);
            return;
        }

        if (w == 0 || w > geo->width)
            w = geo->width;
        x = ptr->win_x;
        if (x < w / 2)
            x = 0;
        else if (x >= (int)geo->width - (w / 2))
            x = geo->width - w;
        else
            x -= w / 2;

        if (h == 0 || h > geo->height)
            h = geo->height;
        y = ptr->win_y;
        if (y < h / 2)
            y = 0;
        else if (y >= (int)geo->height - (h / 2))
            y = geo->height - h;
        else
            y -= h / 2;
    }
    else
    {
        int max;

        x = sys->x;
        max = (int)geo->width - x;
        if (max <= 0)
            goto discard;
        if (w == 0 || w > max)
            w = max;

        y = sys->y;
        max = (int)geo->height - y;
        if (max <= 0)
            goto discard;
        if (h == 0 || h > max)
            h = max;
    }

    /* Update elementary stream format (if needed) */
    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;
        }

        block = block_shm_Alloc (shm, size);
        if (unlikely(block == NULL))
            shmdt (shm);
    }
noshm:
#endif
    if (block == NULL)
    {   /* Capture screen through socket (fallback) */
        xcb_get_image_reply_t *img;

        img = xcb_get_image_reply (conn,
            xcb_get_image (conn, XCB_IMAGE_FORMAT_Z_PIXMAP, drawable,
                           x, y, w, h, ~0), NULL);
        if (img == NULL)
            return;

        uint8_t *data = xcb_get_image_data (img);
        size_t datalen = xcb_get_image_data_length (img);
        block = block_heap_Alloc (img, data + datalen - (uint8_t *)img);
        if (block == NULL)
            return;
        block->p_buffer = data;
        block->i_buffer = datalen;
    }

    /* Send block - zero copy */
    if (sys->es != NULL)
    {
        block->i_pts = block->i_dts = mdate ();

        es_out_Control (demux->out, ES_OUT_SET_PCR, block->i_pts);
        es_out_Send (demux->out, sys->es, block);
    }
}
Beispiel #15
0
int createSharedMemory() {
	key_t key = ftok("producer", 'x');

	return shmget(key, bufferSize(BUFFERSIZE), IPC_CREAT | 0666);
}
Beispiel #16
0
//@ 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;
}
Beispiel #17
0
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, ((stat == 0) ? "rb" : "r+b")))) 
				goto openedinvpost;
			invflipname(invpost, INVPOST, INVPOST2); /* change back for err msg */
		} else if (!invflipname(invpost, INVPOST, INVPOST2)) {
			if ((invcntl->postfile = vpfopen(invpost,((stat == 0)?"rb":"r+b")))) 
				goto openedinvpost;
			invflipname(invpost, INVPOST2, INVPOST); /* change back for err msg */
		}
		invcannotopen(invpost);
		goto closeinv;
	}
openedinvpost:
	/* allocate core for a logical block  */
	if ((invcntl->logblk = malloc((unsigned) invcntl->param.sizeblk)) == NULL) {
		invcannotalloc((unsigned) invcntl->param.sizeblk);
		goto closeboth;
	}
	/* allocate for and read in superfinger  */
	read_index = 1;
	invcntl->iindex = NULL;
#if SHARE
	if (invcntl->param.share == 1) {
		key_t shm_key;
		struct shmid_ds shm_buf;
		int	shm_id;

		/* see if the shared segment exists */
		shm_key = ftok(invname, 2);
		shm_id = shmget(shm_key, 0, 0);
		/* Failure simply means (hopefully) that segment doesn't exists */
		if (shm_id == -1) {
			/* Have to give general write permission due to AMdahl not having protected segments */
			shm_id = shmget(shm_key, invcntl->param.supsize + sizeof(long), IPC_CREAT | 0666);
			if (shm_id == -1)
				perror("Could not create shared memory segment");
		} else
			read_index = 0;

		if (shm_id != -1) {
			invcntl->iindex = shmat(shm_id, 0, ((read_index) ? 0 : SHM_RDONLY));
			if (invcntl->iindex == (char *)ERR) {
				fprintf(stderr, "%s: shared memory link failed\n", argv0);
				invcntl->iindex = NULL;
				read_index = 1;
			}
		}
	}
#endif
	if (invcntl->iindex == NULL)
	        /* FIXME HBB: magic number alert (4) */
		invcntl->iindex = malloc((unsigned) invcntl->param.supsize
					 + 4 *sizeof(long));
	if (invcntl->iindex == NULL) {
		invcannotalloc((unsigned) invcntl->param.supsize);
		free(invcntl->logblk);
		goto closeboth;
	}
	if (read_index) {
		fseek(invcntl->invfile, invcntl->param.startbyte, SEEK_SET);
		fread(invcntl->iindex, (int) invcntl->param.supsize, 1,
		      invcntl->invfile);
	}
	invcntl->numblk = -1;
	if (boolready() == -1) {
	closeboth:
		fclose(invcntl->postfile);
	closeinv:
		fclose(invcntl->invfile);
		return(-1);
	}
	/* write back out the control block if anything changed */
	invcntl->param.filestat = stat;
	if (stat > invcntl->param.filestat ) {
		rewind(invcntl->invfile);
		fwrite(&invcntl->param, sizeof(invcntl->param), 1, invcntl->invfile);
	}
	return(1);
}
Beispiel #18
0
bool linda_init()
{
	//Create virtual memory key
	key_t key = ftok(FTOK_PATH, 1);
	
	if(linda_logging)
		openlog("linda", LOG_PID, 0);
	
	if(key == (key_t) -1)
	{
		printf("IPC error: ftok: %d", errno);
		if(linda_logging)
			syslog(3, "IPC error: ftok: %d", errno);

		closelog();
		return false;
	}
	
	//Allocate a shared memory segment.
	linda_segment_id = shmget(key, sizeof(struct mem), IPC_CREAT | 0660);
	if(linda_segment_id == -1)
	{
		printf("IPC error: shmget: %d", errno);
		if(linda_logging)
			syslog(3, "IPC error: shmget: %d", errno);
		
		closelog();
		return false;
	}
	
	//Map shared memory to our VM
	linda_memory = (struct mem *) shmat (linda_segment_id, NULL, 0);
	if(linda_memory == NULL)
	{
		printf("IPC error: linda_memory: %d", errno);
		if(linda_logging)
			syslog(3, "IPC error: linda_memory: %d", errno);
		
		closelog();
		return false;
	}

	//Check number of currently attached processes. If we are the first process, we are obligated to initialize the memory
	struct shmid_ds shm_data;
	if(shmctl(linda_segment_id, IPC_STAT, &shm_data) == -1)
	{
		printf("IPC error: shmctl(): %d", errno);
		if(linda_logging)
			syslog(3, "IPC error: shmctl(): %d", errno);
		
		closelog();
		return false;
	}

	//Init tuple_count, if it's first process
	if(shm_data.shm_nattch == 1)
	{
		printf("-> Initializing!\n");
		
		//mem_mutex
		pthread_mutexattr_t mem_mutex_attr;
		pthread_mutexattr_init(&mem_mutex_attr);
		pthread_mutexattr_setpshared(&mem_mutex_attr, PTHREAD_PROCESS_SHARED);
		pthread_mutex_init(&linda_memory->mem_mutex, &mem_mutex_attr);
		pthread_mutexattr_destroy(&mem_mutex_attr);
		
		//output_cond
		pthread_condattr_t output_cond_attr;
		pthread_condattr_init(&output_cond_attr);
		pthread_condattr_setpshared(&output_cond_attr, PTHREAD_PROCESS_SHARED);
		pthread_cond_init(&linda_memory->output_cond, &output_cond_attr);
		pthread_condattr_destroy(&output_cond_attr); 
		
		linda_memory->tuple_count = 0;
	}
	
	return true;
}
Beispiel #19
0
int main(int argc,char* argv[])
{
	int shmid;
	int proj_id;
	key_t key;
	int shm_size;
	char* shm_addr,*addr;
	pid_t pid;
	
	if(argc!=3){
		printf("Usage: %s shared_memory_size info\n",argv[0]);
		return 1;
	}

	shm_size=atoi(argv[1]);

	proj_id=2;
        key=ftok("/home/program",proj_id);
        if(key==-1){
                perror("cannot generate the IPC key");
                return 1;
        }

	shmid=shmget(key,shm_size,IPC_CREAT | 0660);
	if(shmid==-1){
		perror("cannot create a shared memory segment");
		return 1;
	}

	addr=(char*)shmat(shmid,NULL,0);
	shm_addr=addr;
	if(shm_addr==(char*)(-1)){
		perror("cannot attach the shared memory to process");
		return 1;
	}

	printf("====address information===\n");
	printf("etext address: %x\n",&etext);
	printf("edata address: %x\n",&edata);
	printf("end address: %x\n",&end);
	printf("shared memory segment address: %x\n",shm_addr);
	printf("==========================\n");
	
	strcpy(shm_addr,argv[2]);

	printf("the input string is : %s\n",argv[2]);
	
	printf("before fork,in shared memory segment the string is: %s\n",shm_addr);
	pid=fork();
	if(pid==-1){
		perror("cannot create new process");
		return 1;
	}else if(pid==0){
		printf("in child process, the string is %s \n",shm_addr);
		printf("modify the content in shared memory\n");
		
		*shm_addr +=1;	
		
		_exit(0);			
	}else{
		wait(NULL);

		printf("after fork, in shared memory segment the string is %s\n",shm_addr);
		if(shmdt(shm_addr)==-1){
			perror("cannot release the memory");
			return 1;
		}
		
		if(shmctl(shmid,IPC_RMID,NULL)==-1){
			perror("cannot delete existing shared memory segment");
			return 1;
		}
	}

	return 0;
}
Beispiel #20
0
int main(int argc, char *argv[])
{
	uint8_t *tab_rp_bits;
	uint16_t *tab_rp_registers;
	uint16_t *rd_position_registers;
    uint16_t *tab_rp_registers_bad;
    modbus_t *ctx;

/***********************************************************************
* feedback is used to store the return value of every called function
* rc is used to store the return value of the modbus command 
* resend is used to define the resend times if the command is failed
* i is used for the loop parameter
* insert_bit is used to indicate the calibarate function if there is value to set
* num is used to store the number of data blocks in database 
* use_backend is used to indicate the modbus mode is rtu
* next_option is used to take the command options
* pre_step, curr_step are used to indicate the previous step number and current position step number
* pre_length and value indicate the latest posiotion in database and current position
* SLEN is a kind of struct used to store the database blocks
************************************************************************/
    int feedback,i; 
	int insert_bit, nb_points,num =0;
	int next_option;
	long curr_step;
	double value;
	double pdepth,pspacing,pdwell,pinterval;
	double profiled,stopped;
	double depth,dwell,spacing,interval;
	double last_position;
	int profilebit =0,feedback1,feedback2;
	int modbus=0;
	int motor_stop = 0;
	char * command_arg = "";
	char * return_value;
	double in_position = 0;
	SLEN *examp;
	ARF  *config, *profile,*off_set;
	modbus_mapping_t *mb_mapping;
	int   ShmID;      
	int *ShmPTR;
	int stop_indicator = 0;

	key_t MyKey;
	MyKey   = ftok(".", 's');    
    ShmID   = shmget(MyKey, sizeof(int), IPC_CREAT | 0666);
    ShmPTR  = (int *) shmat(ShmID, NULL, 0);

	tab_rp_registers = (uint16_t *) malloc(4 * sizeof(uint16_t));
	rd_position_registers = (uint16_t *) malloc(2 * sizeof(uint16_t));
	tab_rp_registers_bad = (uint16_t *) malloc(2 * sizeof(uint16_t));

	config = (ARF*)malloc( 10 * sizeof(ARF) );
	if ( config == NULL ) 
	{
		printf("Error: Out of Memory, use ./master reset to reset memory\n"); 
		exit(1);
	}
	const char *const short_options = "hd::u::l:p::cD::w::s::i::gSmt::";
	const struct option long_options[] = {
        { "help",              0,NULL, 'h'},
        { "down",              2,NULL, 'd'},
		{ "up",                2,NULL, 'u'},
		{ "length",            1,NULL, 'l'},
		{ "position",          2,NULL, 'p'},
		{ "count",             0,NULL, 'c'},
		{ "Depth",             2,NULL, 'D'},
		{ "well",              2,NULL, 'w'},
		{ "spacing",           2,NULL, 's'},
		{ "interval",          2,NULL, 'i'},
		{ "go",                0,NULL, 'g'},
		{ "System",            0,NULL, 'S'},
		{ "motor",             0,NULL, 'm'},
		{ "time",              2,NULL, 't'},
        { NULL, 0, NULL, 0  },

    };

	if (argc < 2) 
	{
		print_comusage (stderr, 1);
		return_value = json_option("status:",-1);
		return return_value;
	}
	program_name = argv[0];
	/*Get the first argument that passed through main function but does not contain*/
	command_name = argv[1];
	if(argc > 2)
	{
		command_arg  = argv[2];
	}
/*******************************************************************************************
* The next three command_name are used to control the motor through modbus	(need modbus)  *
********************************************************************************************/

	if ( strcmp(command_name, "go") == 0 ) {
		double curr_position;
		char *recd = (char*)malloc(10*sizeof(char));
		double offset;
		int re_send = 0;
		*ShmPTR = 0;
		modbus = 1;
		next_option = getopt_long (argc, argv, short_options, long_options, NULL);
		
		if (next_option == -1) print_comusage (stderr, 1);
		while (next_option != -1) 
		{
			switch (next_option) 
			{
				case 'h':
						print_comusage(stdout, 0);
				case 'd':  
				godown:
						enable(0);
						initbus(1);
						sleep(1);
						ctx = modbusconnection(ctx);
						modbus = 1;
						feedback = godown(ctx);
						if((feedback == -1)&&(re_send <1))
						{
							enable(0);
							initbus(0);
							re_send++;
							goto godown;
						}
						return_value = json_option("status",feedback);
						printf("%s\n",return_value);
						break;	
				case 'u':
				goup: 
						enable(0);
						initbus(1);
						sleep(1);
						ctx = modbusconnection(ctx);
						modbus = 1;
						feedback = goup(ctx);
						if((feedback == -1)&&(re_send <1))
						{
							enable(0);
							initbus(0);
							re_send++;
							goto goup;
						}
						return_value = json_option("status",feedback);
						printf("%s\n",return_value);
						break;	
				case 'p':
						enable(0);
						initbus(1);
						sleep(1);
						ctx = modbusconnection(ctx);
						modbus = 1;
						in_position = atof(optarg);		
						off_set = (ARF*)malloc(15*sizeof(ARF));
	    				off_set = getconfig(&num,off_set);
						offset = off_set[10].value;
						in_position = in_position - offset;
						free(off_set);
						//system("/home/sampler/kingkong.sh");
				gotoposition:
						if (in_position <= 0)gotoposition(ctx,0,rd_position_registers);
						else 
						{
							curr_position = checkposition(ctx,rd_position_registers);
							//printf("Position is %lf\n",curr_position);
							if ( !(( (in_position -0.1) <= curr_position ) && ( curr_position <= (in_position + 0.1) )) ) 
							{
								feedback = gotoposition(ctx, in_position,rd_position_registers);
								return_value = json_option("status",feedback);
								//printf("%s\n",return_value);
							}
						}
						if((feedback == -1)&&(re_send <1))
						{
							enable(0);
							initbus(0);
							enable(0);
							initbus(1);
							sleep(1);
							ctx = modbusconnection(ctx);
							re_send++;
						}
						break;	
					case '?':
						print_comusage (stderr, 1);
					default:
						abort ();
				}
			next_option = getopt_long (argc, argv, short_options, long_options, NULL);
		}	
		//If the go command is failed, then exit the current process and power off the controller 
		if(feedback == -1)
		{
			*ShmPTR = 1;
			enable(0);
			initbus(0);
			return_value = json_option("status",-1);
			return return_value;
		}
		//wait_stop(ShmPTR,ctx,tab_rp_registers);
		do {
			sleep(1); 
			stop_indicator = *ShmPTR;              
		}while ((checkmotorstatus(ctx,tab_rp_registers)!= 0 ) && (stop_indicator != 1)); 
		sleep(1);
		//In order to avoid loop in checking position, get rid of using do-while   
		curr_position = checkposition(ctx,rd_position_registers);
		if(curr_position != -1)
		{
			login("Go to command set last position");
			curr_position = curr_position + offset;
			setconfig(9,curr_position);
			// In order to avoid "Read status command shutdown the power by accident"
			if( *ShmPTR == 0)
			{
				enable(0);
				initbus(0);	
				*ShmPTR = 1;
			}	
			return_value = json_option("status",1);
		}
		else return_value = json_option("status",-1);
	}

	if ( strcmp(command_name, "stop") == 0 ) 
	{ 		
		if(check_power() == 1)
		{
			sleep(1);
			ctx = modbusconnection(ctx);
			modbus = 1;
			feedback = stop(ctx);
			if(feedback == -1)stop(ctx);
		}
	}

    if ( strcmp(command_name, "position") == 0 ) 
	{ 
		login("Check position command");
		int resend = 0;
		double temp_position,offset;
		char *rec = (char*)malloc(10*sizeof(char));
		stop_indicator = *ShmPTR;
		uint16_t * position_registers = (uint16_t *) malloc(2 * sizeof(uint16_t));
		off_set = (ARF*)malloc(15*sizeof(ARF));
	    off_set = getconfig(&num,off_set);
		offset = off_set[10].value;
checkposition:
		if (check_power()== 1) 
		{
			ctx = modbusconnection(ctx);
			modbus = 1;
			temp_position = checkposition(ctx,position_registers);
			sprintf(rec,"The position read is %f",temp_position);
			login(rec);
			if(temp_position != -1)
			{
				login("Check position set last position");
				//This sentence is used to show the position with offset 
				temp_position = temp_position + offset;
				feedback = setconfig(9,temp_position);
			}
			else 
			{
				if(resend < 2)
				{
					resend++;					
					goto checkposition;
				}
				else return -100;
			}
		}
		else 
		{
			config = getconfig(&num,config);
			temp_position = config[8].value;
		}
		return_value = json_float_option("status",temp_position);
		printf("%s\n",return_value);
	}
/***********************************************************************
*         0: motor is stopped                                          *
*         1: motor is going down                                       *
*         2: motor is going up                                         *
*         3: motor is ramp up                                          *
*         4: motor is ramp down   									   *
*		   (need modbus)             						           *
*                                               	                   *
************************************************************************/
	if(strcmp(command_name, "status") == 0) 
	{
		stop_indicator = *ShmPTR;
		if (check_power()== 1) 
		{
			sleep(1);
			ctx = modbusconnection(ctx);
			modbus = 1;
			next_option = getopt_long (argc, argv, short_options, long_options, NULL);
			if(next_option == -1) print_comusage (stderr, 1);
			while(next_option != -1) 
			{
				switch (next_option) 
				{
					case 'h':
							print_comusage(stdout, 0);	
					case 'S':
							feedback = checksystemstatus(ctx,tab_rp_registers);
							return_value = json_option("status",feedback);
							break;	
					case 'm':
							feedback = checkmotorstatus(ctx,tab_rp_registers);
							return_value = json_option("status",feedback);
							break;
					case '?':
							print_comusage (stderr, 1);
					default:
							abort ();
				}
				next_option = getopt_long (argc, argv, short_options, long_options, NULL);
			}	
			if(feedback == -1)
			{
				return_value = json_option("status",0);
			}
		}
		else 
		{
			return_value = json_option("status",0);
			//login("Check status from database");
		}
		printf("%s\n",return_value);
	}

/****************************************************************************************
*      The next three command_name are used to control the database through sqlite3	    *
*****************************************************************************************/
	if ( strcmp(command_name, "factory_default") == 0 ) 
	{
		feedback1 = reset(0);
		feedback2 = dbinit(0);
		if ( (feedback1 == 1) && (feedback2 == 1)) 
		{
			return_value = json_float_option("status",1);
			printf("%s\n",return_value);
		}
		else 
		{
			return_value = json_float_option("status",-1);
			printf("%s\n",return_value);		
		}
	}

	if ( strcmp(command_name, "reset") == 0 ) 
	{
		feedback = reset(0);
		if(feedback == 1)
		{
			feedback = expected_time_reset();
		}
		return_value = json_float_option("status",feedback);
		printf("%s\n",return_value);
	}

	if ( strcmp(command_name, "init") == 0 ) 
	{
		feedback = -1;
		if ( strcmp(command_arg, "all") == 0 ) 
		{
			feedback = dbinit(0);
			if(feedback == 1)
			{
				feedback = expected_time_init();
			}
		}
		if ( strcmp(command_arg, "calibrate" ) == 0 ) 
		{ 
			setconfig(6,0);
			feedback = dbinit(1); 
		}
		if ( strcmp(command_arg, "configure" ) == 0 ) 
		{
			feedback = dbinit(2);
		}
		if ( feedback == -1 ) 
		{
			return_value = json_float_option("status",-1);
			print_comusage (stderr, 1);
		}
		else return_value = json_float_option("status",feedback);
		printf("%s\n",return_value);
	}

	if ( strcmp(command_name,"get") == 0 ) 
	{
		examp = getall(&num,examp);
		return_value = json_array_option(num,examp);
		free(examp);
		printf("%s",return_value);
	}
	if ( strcmp(command_name,"set_offset") == 0 ) 
	{
		double offset;		
		next_option = getopt_long (argc, argv, short_options, long_options, NULL);
		if ( next_option == -1 ) print_comusage (stderr, 1);
		while( next_option != -1 ) 
		{
			switch (next_option) 
			{
				case 'h':
						print_comusage(stdout, 0);	
				case 'l':
						if(optarg!=0)offset = strtod(optarg,NULL);
						insert_bit = 1;
						break;	
				case '?':
						print_comusage (stderr, 1);
				default:
						abort ();
			}
			next_option = getopt_long (argc, argv, short_options, long_options, NULL);
		}	
		feedback = setconfig(11,offset);
		return_value = json_option("status",feedback);
		printf("%s",return_value);
	}
	if ( strcmp(command_name,"get_offset") == 0 ) 
	{
		double offset;		
		off_set = (ARF*)malloc(15*sizeof(ARF));
	    off_set = getconfig(&num,off_set);
		offset = off_set[10].value;
		return_value = json_float_option("status",offset);
		printf("%s",return_value);	
		free(off_set);
	}
/**************************************************************************
*      The next three command_name are used to calibrate (need modbus)     *                     
***************************************************************************/
	if ( strcmp(command_name, "calibrate") == 0 ) 
	{	
		double calibrate;
		enable(0);
		initbus(1);
		sleep(1);
		ctx = modbusconnection(ctx);	
		modbus = 1;	
		next_option = getopt_long (argc, argv, short_options, long_options, NULL);

		if ( next_option == -1 ) print_comusage (stderr, 1);
		config = getconfig(&num,config);
		calibrate = config[5].value;
		if ( calibrate == 0 ) 
		{
			reset(1);
			setconfig(6,1.0);
			set(num,0,0);
		}
		while( next_option != -1 ) 
		{
			switch (next_option) 
			{
				case 'h':
						print_comusage(stdout, 0);	
				case 'l':
						if(optarg!=0)value = atof(optarg);
						insert_bit = 1;
						break;	
				case 'c':
						getall(&num,examp);
						return_value = json_option("status",num);
						printf("%s\n",return_value);
						break;
				case '?':
						print_comusage (stderr, 1);
				default:
						abort ();
			}
			next_option = getopt_long (argc, argv, short_options, long_options, NULL);
		}	
		if ( insert_bit == 1 ) 
		{
			curr_step = checksteps(ctx,rd_position_registers);
			if ( curr_step < 0 ) curr_step =0;//do not need
			feedback = checkvalue(curr_step,value);
			if ( feedback == 1 ) 
			{
				feedback = set(num,curr_step,value);
				return_value = json_option("status",feedback);
			} 
			else 
			{
				return_value = json_option("status",-1);
			}	
		}
		/*if ( checkmotorstatus(ctx,tab_rp_registers) == 0 ) 
		{	
			enable(0);
			initbus(0);
		}*/
		printf("%s\n",return_value);
	}


/***********************************************************************
*         The following functions are used for profile				   *
*                                               	                   *
************************************************************************/
	if ( strcmp(command_name, "profile") == 0 ) 
	{
		next_option = getopt_long (argc, argv, short_options, long_options, NULL);
		if ( next_option == -1 ) print_comusage (stderr, 1);
		while ( next_option != -1 ) 
		{
			switch (next_option) {
				case 'h':
						print_comusage(stdout, 0);	
				case 'd':
						if(optarg!=0)depth = atof(optarg);
						profilebit = 1;
						break;	
				case 's':
						if(optarg!=0)spacing = atof(optarg);
						profilebit = 1;
						break;
				case 'w':
						if(optarg!=0)dwell = atof(optarg);
						profilebit = 1;
						break;
				case 'i':
						//if(optarg!=0)interval = atof(optarg);
						if(optarg!=0)interval = strtod(optarg,NULL);
						profilebit = 1;
						break;
				case '?':
						print_comusage (stderr, 1);
				default:
						abort ();
				}
			next_option = getopt_long (argc, argv, short_options, long_options, NULL);
		}	

		if ( profilebit == 1 ) 
		{
			feedback = set_profile(depth,spacing,dwell,interval);
		}
		//Want to get the expected profile time and save it in database
		profile_time_check(interval);
		return_value = json_float_option("status",feedback);
		printf("%s\n",return_value);
	}

	if ( strcmp(command_name, "profileget" ) == 0) 
	{
		profile = getconfig(&num,config);
		return_value = json_profile_option(num-2,profile);
		free(profile);
		printf("%s",return_value);	
	}
	if ( strcmp(command_name, "profile_check" ) == 0) 
	{
		int *expected_profile_time;
		long remain_profile_time;
		config = getconfig(&num,config);
		pinterval = config[3].value;
		if(pinterval == 0)	
		{
			printf("-999\n");
			return -999;
		}
		expected_profile_time = (int*)malloc(10*sizeof(int));
		if(expected_profile_time == NULL){printf("error\n");exit(1);}
		expected_time_get(expected_profile_time);
		remain_profile_time = auto_run(0,expected_profile_time);
		if(remain_profile_time <=0 )remain_profile_time = 0;
		printf("%d\n",remain_profile_time);
		free(expected_profile_time);
		return remain_profile_time;
	}
	if ( strcmp(command_name, "profile_reset") == 0 ) 
	{
		//feedback = dbinit(2);
		//reading_hourly();
		system("ps aux | grep -e 'master profilego' | grep -v grep | awk '{print $2}' | xargs -i kill {}");
		feedback = set_profile(0,0,0,0);
		return_value = json_float_option("status",feedback);
		printf("%s\n",return_value);
	}

	if ( strcmp(command_name, "profilego") == 0 ) 
	{	
		double stayposition, curr_position,tmp,cal_position;
		double sdl_read,offset;
		long wait_time,motor_status;
		int year;
		time_t fail_time;
		modbus_t *sdl;
		int count,fini_count,re_try1 = 0,re_power1 =0,re_try = 0,re_send=0;
		int i=1,sample = 0,profile_times,sample_indicator;
		int * expected_tm, *curr_time,inter_val;
		*ShmPTR = 0;
		setconfig(10,0);
		//Will get the expected time from database and compare if it is roughly 
	profile:
		config = getconfig(&num,config);
		pdepth = config[0].value;
		pspacing = config[1].value;
		pdwell = config[2].value;
		pinterval = config[3].value;	
		profiled = config[4].value;
		sample = config[9].value;
		offset = config[10].value;
		profile_times = 1+(pdepth - offset)/pspacing;
		inter_val = (int)pinterval;
		if(pinterval == 0){schedule_reading();goto profile;}
	   	if(profiled == 0 )
		{
			config = getconfig(&num,config);
			pdepth = config[0].value;
			pspacing = config[1].value;
			pdwell = config[2].value;
			pinterval = config[3].value;	
			profiled = config[4].value;
			sample = config[9].value;
			expected_tm = (int*)malloc(10*sizeof(int));
			curr_time = (int*)malloc(10*sizeof(int));
			if(curr_time == NULL){printf("error\n");exit(1);}
			if(expected_tm == NULL){printf("error\n");exit(1);}
			do{
				config = getconfig(&num,config);
				sample = config[9].value;
				expected_time_get(expected_tm);
				printf("Profile %d %d %d %d %d %d\n",expected_tm[0],expected_tm[1],expected_tm[2],expected_tm[3],expected_tm[4],expected_tm[5]);
				wait_time= auto_run(0,expected_tm);
				printf("Wait for %ds to profile\n",wait_time);
				curr_time = check_time(curr_time);
				printf("NOW %d %d %d %d %d %d\n",curr_time[0],curr_time[1],curr_time[2],curr_time[3],curr_time[4],curr_time[5]);
				sample_indicator = curr_time[3]%inter_val;
				//printf("%d\n",sample_indicator);
				if(wait_time < -600)
				{
					profile_time_check(pinterval);
					goto profile;
				}				
			}while(wait_time>0);
			printf("quit\n");
			free(expected_tm);	
			printf("free\n");
		four_minute_delay:
			sleep(1);
			curr_time = check_time(curr_time);
			if((curr_time[4]>=4) &&(curr_time[4]<=10))goto start_profile;
			if(curr_time[4]<4)goto four_minute_delay;
			if(curr_time[4]>10)goto profile;
		}
	start_profile:
		printf("start profile\n");
		if(profiled == 0)process_profile(3,1,profile_times,0);
		enable(0);
		initbus(1);
		sleep(1);
		ctx = modbusconnection(ctx);
		if(ctx == NULL)goto profile;
		modbus = 1;
		sleep(1);
		if ( profiled == 0 ) 
		{			
			login("Start Profiling");
	        //Before go home, we do not need to check if it is home. 
			gotoposition(ctx, 0,rd_position_registers);
			wait_for_stop(ctx, tab_rp_registers);
			//Set the profile flag 
			setconfig(5,1);
		sdl_profile:
			sdl = sdl_connection(sdl);	
			if(sdl == NULL)
			{
				if(re_try < 2){re_try++;goto sdl_profile;}
				login("Failed in connecting in profile duration");
				setsdl(30000,-100000);
			}
			else 
			{
				curr_time = check_time(curr_time);
				year = curr_time[0] -2000;
				sdl_rtc_time(sdl,year,curr_time[1],curr_time[2],curr_time[3],curr_time[4],curr_time[5]);
				sleep(1);
				sdl_start_profile(sdl,profile_times);
			}
			modbus_close(sdl);
			initbus(0);
			sleep(pdwell);
		}	
		enable(0);
		initbus(1);
		sleep(1);
		ctx = modbusconnection(ctx);
		//This following part is used to determine where is destination  
		curr_position = checkposition(ctx,tab_rp_registers) + offset;
		cal_position = i*pspacing + offset;
		if ( cal_position < pdepth )
		{
			stayposition = cal_position;
		}
		else 
			stayposition = pdepth;
		i++;
		stayposition = stayposition - offset;
		gotoposition(ctx,stayposition,tab_rp_registers);
position1:
			sleep(1);		
			ctx = modbusconnection(ctx);
			curr_position = checkposition(ctx,tab_rp_registers) + offset;
			if(curr_position == -1)
			{
				if(re_power1 < 3)
				{		
					if(re_try1 < 2)
					{
						sleep(3);
						re_try1++;
						goto position1;
					}
					else
					{
						re_try1 = 0;
						enable(0);
						initbus(0);
						sleep(3);
						initbus(1);
						sleep(1);
						re_power1++;
						goto position1;
					}
				}
				else
				{
					enable(0);
					initbus(0);
					enable(1);
					re_power1 = 0;
					return -1;
				}
			}
			if (!((stayposition -0.1) <= curr_position ) && (curr_position <= (stayposition + 0.1)))goto position1;

		wait_for_stop(ctx, tab_rp_registers);
		//Here check position in order to determine if it is destination now 
		curr_position = checkposition(ctx,tab_rp_registers)+offset;
		setconfig(9,curr_position);
		printf("Go to sleep for dwell time\n");
		initbus(0);
		sleep(pdwell);
		if (((pdepth -0.1) <= curr_position) && (curr_position <= (pdepth + 0.1))) 
		{ 
			
			setconfig(5,0);
			profile_time_check(pinterval);
			enable(0);
			initbus(1);
			ctx = modbusconnection(ctx);
			gotoposition(ctx, 0,rd_position_registers);
			wait_for_stop(ctx, tab_rp_registers);
			sleep(1);
			enable(0);
			initbus(0);
			enable(1);
			//Save the position 0, set need_sleep to 0 and set stop indicate bit ShmPTR eqaul 1 
			setconfig(9,offset);
			//Read the SDL data and store it in database
			sleep(40);
		}
		goto profile;
	}
/***********************************************************************
*          The next three command_name are used                        *
*             to control the date and time         	                   *
************************************************************************/
	if ( strcmp(command_name, "checktime") == 0 ) 
	{
		char *sdate;
		if ( (sdate = malloc( 80 * sizeof(char) ) )== NULL)return NULL; 
		sdate = current_time(sdate);
		return_value = json_option_string("status",sdate);
		printf("%s\n",return_value);
		free(sdate);
    }
	if ( strcmp(command_name, "settime") == 0 ) 
	{
    	if ( argc < 4 ) 
		{ 
			print_comusage (stderr, 1); 
		}
        char *date = argv[2];
        char *time = argv[3];
        int *buf = (int*)malloc(6*sizeof(int)); 
		parse(buf,date,time);
        int i,m_buf[6];
        for(i=0;i<=5;i++) 
		{ 
			m_buf[i]=*(buf+i); 
		}
		feedback = set_time(&m_buf);
        return_value = json_option("status:",feedback);
        printf("%s\n",return_value);
		login("Set local time");
		login(return_value);
		sleep(5);
	}
	if ( strcmp(command_name, "voltage") == 0 ) 
	{
		double voltage;	
		voltage = voltage_read();
		return_value = json_float_option("status",voltage);
		printf("%s\n",return_value);
	}
	if ( strcmp(command_name, "temp") == 0 ) 
	{
		double temp;
		temp = temp_read();
		return_value = json_float_option("status",temp);
		printf("%s\n",return_value);
	}
	if(strcmp(command_name, "enable_power") == 0)
	{
		enable(0);
		initbus(1);
		return_value = json_option("status:",1);
	}

	if(strcmp(command_name, "disable_power") == 0)
	{
		enable(0);
		initbus(0);
		return_value = json_option("status:",1);
	}
	if ( strcmp(command_name, "backup") == 0 ) 
	{
		feedback = system("cp /home/sampler/lr.sl3   /home/sampler/lr_default.sl3");
		if(feedback == -1)
		{
			return_value = json_float_option("status",-1);
		}
		else return_value = json_float_option("status",1);
		printf("%s\n",return_value);
	}
	if ( strcmp(command_name, "restore") == 0 ) 
	{
		feedback = system("cp /home/sampler/lr_default.sl3  /home/sampler/lr.sl3");
		if(feedback == -1)
		{
			return_value = json_float_option("status",-1);
		}
		else return_value = json_float_option("status",1);
		printf("%s\n",return_value);
	}
	if ( strcmp(command_name, "debug") == 0 ) 
	{
		long return_steps;
		char *debug_result;
		enable(0);
		initbus(1);
		sleep(1);
		ctx = modbusconnection(ctx);
		modbus = 1;
		uint16_t *debug_position_registers = (uint16_t*)malloc(2*sizeof(uint16_t));
		debug_result = (char*)malloc(50*sizeof(char));
		return_steps = checksteps(ctx,debug_position_registers);
		sprintf(debug_result,"%x,%x,%x\n",debug_position_registers[0],debug_position_registers[1],return_steps);
		json_option_string("status",debug_result);
		printf("%s\n",debug_result);
		initbus(0);
		
	}
	if ( strcmp(command_name, "power_check") == 0 ) 
	{
		int power_status = check_power();
		printf("Power is %d\n",power_status);
	}
	if ( strcmp(command_name, "sdl") == 0 ) 
	{
		modbus_t * sdl;
		sdl = sdl_connection(sdl);	
		if(sdl != NULL)
		{
			double vol = sdltest(sdl);
			return_value = json_float_option("status",vol);
			printf("%s\n",return_value);
			setsdl(30000,vol);
			login("Read SDL");
			login(return_value);
		}
		else setsdl(30000,-100000);
		modbus_close(sdl);
  		modbus_free(sdl);
	}
	if ( strcmp(command_name, "sdl_reset") == 0 ) 
	{
		resetsdl();
	}
	if ( strcmp(command_name, "sdl_get") == 0 ) 
	{
		int num_records;		
		SLEN * sdl_records;
		sdl_records = (SLEN*)malloc(100*sizeof(SLEN));
		sdl_records = getsdl(&num_records, sdl_records);
		return_value = json_sdl_option(num_records,sdl_records);
		printf("%s\n",return_value);
		free(sdl_records);
	}
	if ( strcmp(command_name, "sdl_uploadtime") == 0 ) 
	{	
		modbus_t * sdl;
		sdl = sdl_connection(sdl);	
		if(sdl == NULL)
		{
			setsdl(30000,-100000);
		}
		else sdl_setuploadtime(sdl,12,5,21,12,50,0);
	}
	if ( strcmp(command_name, "sdl_settime") == 0 ) 
	{	
		modbus_t * sdl;
		sdl = sdl_connection(sdl);	
		if(sdl == NULL)
		{
			setsdl(30000,-100000);
		}
		else  sdl_rtc_time(sdl,12,5,25,7,58,0);
	}
	if ( strcmp(command_name, "sdl_readsize") == 0 )
	{
		modbus_t * sdl;
		sdl = sdl_connection(sdl);	
		if(sdl == NULL)
		{
			setsdl(30000,-100000);
		}
		else sdl_readbuffsize(sdl);
	} 
	if ( strcmp(command_name, "sdl_readsensor") == 0 ) 
	{	
		modbus_t * sdl;
		sdl = sdl_connection(sdl);	
		if(sdl == NULL)
		{
			setsdl(30000,-100000);
		}
		else sdl_read_sensor(sdl,1,1);
	}
	if ( strcmp(command_name, "sdl_upload") == 0 ) 
	{
		//sdl_read_log_data(16);
		int number;
		modbus_t * sdl;
		sdl = sdl_connection(sdl);	
		if(sdl == NULL)
		{
			setsdl(30000,-100000);
		}
		else 
		{
			profile_save_data(sdl);
		}
		modbus_close(sdl);
	}
	if ( strcmp(command_name, "sdl_sample") == 0 ) 
	{
		int number;
		modbus_t * sdl;
		sdl = sdl_connection(sdl);	
		if(sdl == NULL)
		{
			setsdl(30000,-100000);
		}
		else 
		{
			sdl_read_sensor(sdl,1,1);
			sleep(60);
			sample_save_data(sdl);
			//sdl_start_profile(sdl,2);
		}
		modbus_close(sdl);
	}
	if ( strcmp(command_name, "shutdown") == 0 ) 
	{
		feedback = system("/sbin/shutdown now");
	}
	if ( strcmp(command_name, "maxstep") == 0 ) 
	{
		enable(0);
		initbus(1);		
		sleep(1);
		ctx = modbusconnection(ctx);
		modbus = 1;
		feedback = set_max_step(ctx,rd_position_registers);
		return_value = json_option("status",feedback);
		initbus(0);
	}
	if(strcmp(command_name, "slave") == 0)
	{
		slave();
	} 
	if(strcmp(command_name, "motor_status") == 0) 
	{
		if (check_power()== 1) 
		{
			sleep(1);
			ctx = modbusconnection(ctx);
			modbus = 1;
			feedback = checkmotorstatus(ctx,tab_rp_registers);
			if(feedback == -1)
			{
				printf("0\n");				
				return 0;
			}
			else 
			{
				printf("%d\n",feedback);
				return feedback;
			}
		}
		else
		{
			printf("0\n");
			return 0;
		}		
	}
close:
	/* Free the memory */
    //free(tab_rp_bits);
	free(config);
    free(tab_rp_registers);
	free(rd_position_registers);
	//modbus_mapping_free(mb_mapping);
    /* Close the connection */
	if (modbus == 1)	
	{
    	modbus_close(ctx);
	}

	if (motor_stop == 1) 
	{
		printf("stop setting\n");
		setconfig(9,last_position);
	}
    return return_value;
}
Beispiel #21
0
int main()
{
  int      server_sockfd, client_sockfd;
  int      server_len, client_len;
  int      res;
  struct   sockaddr_in server_address;
  struct   sockaddr_in client_address;
  struct   sigaction act;
  c_client *shared_limit;

  act.sa_handler = close_server;
  sigemptyset(&act.sa_mask);
  act.sa_flags = 0;
  sigaction(SIGINT, &act, 0);

  shmid = shmget((key_t)123,sizeof(c_client),0666 | IPC_CREAT);
  if (shmid == -1)
  {
      fprintf(stderr,"shmget failed\n");
      exit(EXIT_FAILURE);
  }

  shared_memory = shmat(shmid,(void *)0,0);
  if (shared_memory == (void *)-1)
  {
      fprintf(stderr,"shmat failed\n");
      exit(EXIT_FAILURE);
  }

  shared_limit = (c_client *)shared_memory;

  res = pthread_mutex_init(&shared_limit->count_mutex, NULL);
  if(res != 0)
  {
      perror("Mutex init failed\n");
      exit(EXIT_FAILURE);
  }

  server_sockfd = socket(AF_INET,SOCK_STREAM,0);
  server_address.sin_family = AF_INET;
  server_address.sin_addr.s_addr = inet_addr("127.0.0.1");
  server_address.sin_port = htons(6565);
  server_len = sizeof(server_address);
  bind(server_sockfd, (struct sockaddr *)&server_address, server_len);
  
  listen(server_sockfd, 5);
  signal(SIGCHLD,SIG_IGN);

  while(1)
  {
    int bytes, fd;

    printf("server waititng \n");
    client_len = sizeof(client_address);
    client_sockfd = accept(server_sockfd,(struct sockaddr *)&client_address,&client_len);

    if(shared_limit->curcount >= CLIENT_LIMIT)
    {
        printf("============server clients limit is exceeded! socket will be closed=============\n");
        close(client_sockfd);
    }
    else
        if (fork() == 0)
        {
            pthread_mutex_lock(&shared_limit->count_mutex);
            shared_limit->curcount++;
            printf("clients count = %d\n", shared_limit->curcount);
            pthread_mutex_unlock(&shared_limit->count_mutex);

            printf("connection is init\n");

            memset((void *)msg,(int)'\0',99999);
            read(client_sockfd, msg, sizeof(msg));
            printf("server get this:\n%s\n", msg);

            req_params[0] = strtok(msg, " ");
            if (strncmp(req_params[0], "GET", 4) == 0)
            {
                printf("this is GET query\n");
                req_params[1] = strtok(NULL," ");

                if (strncmp(req_params[1],"/", 2) == 0)
                    req_params[1] = "/index.html";

               if (strstr(req_params[1], "..") != NULL)
                    req_params[1] = "/index.html";

                if ((fd = open(req_params[1] + 1, O_RDONLY)) != -1)
                {
                    server_answer.header = "HTTP/1.1 200 OK\n\n";
                    send(client_sockfd, server_answer.header, strlen(server_answer.header), 0);

                    while((bytes = read(fd, html, PARTBUF_SIZE)) > 0)
                    {
                        write(client_sockfd, html, bytes);
                    }
                    close(fd);
                }
                else
                {
                    server_answer.header = "HTTP/1.1 404 Not Found\n\n";
                    server_answer.body = "<html><body><h1>404 Not Found</h1></body></html>";
                    send(client_sockfd, server_answer.header, strlen(server_answer.header), 0);
                    send(client_sockfd, server_answer.body, strlen(server_answer.body), 0);
                }

                close(client_sockfd);
                pthread_mutex_lock(&shared_limit->count_mutex);
                shared_limit->curcount--;
                printf("clients count = %d\n", shared_limit->curcount);
                pthread_mutex_unlock(&shared_limit->count_mutex);

                exit(EXIT_SUCCESS);
            }
        }
        else
        {
            close(client_sockfd);
        }
  }
} 
/**
 * this routine performs a test that indicates whether or not sysv shared
 * memory can safely be used during this run.
 * note: that we want to run this test as few times as possible.
 *
 * @return OPAL_SUCCESS when sysv can safely be used.
 */
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;

    *priority = 0;
    *module = NULL;

    /* if hint isn't null, then someone else already figured out who is the
     * best runnable component is AND the caller is relaying that info so we
     * don't have to perform a run-time query.
     */
    if (NULL != hint) {
        OPAL_OUTPUT_VERBOSE(
            (70, opal_shmem_base_framework.framework_output,
             "shmem: sysv: runtime_query: "
             "attempting to use runtime hint (%s)\n", hint)
        );
        /* was i selected? if so, then we are done.
         * otherwise, disqualify myself.
         */
        if (0 == strcasecmp(hint,
                            mca_shmem_sysv_component.super.base_version.mca_component_name)) {
            *priority = mca_shmem_sysv_component.priority;
            *module = (mca_base_module_t *)&opal_shmem_sysv_module.super;
            return OPAL_SUCCESS;
        }
        else {
            *priority = 0;
            *module = NULL;
            return OPAL_SUCCESS;
        }
    }

    /* if we are here, then let the run-time test games begin */
    OPAL_OUTPUT_VERBOSE(
        (70, opal_shmem_base_framework.framework_output,
         "shmem: sysv: runtime_query: NO HINT PROVIDED:"
         "starting run-time test...\n")
    );

    if (-1 == (shmid = shmget(IPC_PRIVATE, (size_t)(opal_getpagesize()),
                              IPC_CREAT | IPC_EXCL | S_IRWXU ))) {
        goto out;
    }
    else if ((void *)-1 == (addr = shmat(shmid, NULL, 0))) {
        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_shmem_sysv_component.priority;
        *module = (mca_base_module_t *)&opal_shmem_sysv_module.super;
    }

out:
    if ((char *)-1 != addr) {
        shmdt(addr);
    }
    return OPAL_SUCCESS;
}
Beispiel #23
0
/*
 *	InternalIpcMemoryCreate(memKey, size)
 *
 * Attempt to create a new shared memory segment with the specified key.
 * Will fail (return NULL) if such a segment already exists.  If successful,
 * attach the segment to the current process and return its attached address.
 * On success, callbacks are registered with on_shmem_exit to detach and
 * delete the segment when on_shmem_exit is called.
 *
 * If we fail with a failure code other than collision-with-existing-segment,
 * print out an error and abort.  Other types of errors are not recoverable.
 */
static void *
InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size)
{
	IpcMemoryId shmid;
	void	   *memAddress;

	shmid = shmget(memKey, size, IPC_CREAT | IPC_EXCL | IPCProtection);

	if (shmid < 0)
	{
		/*
		 * Fail quietly if error indicates a collision with existing segment.
		 * One would expect EEXIST, given that we said IPC_EXCL, but perhaps
		 * we could get a permission violation instead?  Also, EIDRM might
		 * occur if an old seg is slated for destruction but not gone yet.
		 */
		if (errno == EEXIST || errno == EACCES
#ifdef EIDRM
			|| errno == EIDRM
#endif
			)
			return NULL;

		/*
		 * Some BSD-derived kernels are known to return EINVAL, not EEXIST, if
		 * there is an existing segment but it's smaller than "size" (this is
		 * a result of poorly-thought-out ordering of error tests). To
		 * distinguish between collision and invalid size in such cases, we
		 * make a second try with size = 0.  These kernels do not test size
		 * against SHMMIN in the preexisting-segment case, so we will not get
		 * EINVAL a second time if there is such a segment.
		 */
		if (errno == EINVAL)
		{
			int			save_errno = errno;

			shmid = shmget(memKey, 0, IPC_CREAT | IPC_EXCL | IPCProtection);

			if (shmid < 0)
			{
				/* As above, fail quietly if we verify a collision */
				if (errno == EEXIST || errno == EACCES
#ifdef EIDRM
					|| errno == EIDRM
#endif
					)
					return NULL;
				/* Otherwise, fall through to report the original error */
			}
			else
			{
				/*
				 * On most platforms we cannot get here because SHMMIN is
				 * greater than zero.  However, if we do succeed in creating a
				 * zero-size segment, free it and then fall through to report
				 * the original error.
				 */
				if (shmctl(shmid, IPC_RMID, NULL) < 0)
					elog(LOG, "shmctl(%d, %d, 0) failed: %m",
						 (int) shmid, IPC_RMID);
			}

			errno = save_errno;
		}

		/*
		 * Else complain and abort.
		 *
		 * Note: at this point EINVAL should mean that either SHMMIN or SHMMAX
		 * is violated.  SHMALL violation might be reported as either ENOMEM
		 * (BSDen) or ENOSPC (Linux); the Single Unix Spec fails to say which
		 * it should be.  SHMMNI violation is ENOSPC, per spec.  Just plain
		 * not-enough-RAM is ENOMEM.
		 */
		ereport(FATAL,
				(errmsg("could not create shared memory segment: %m"),
		  errdetail("Failed system call was shmget(key=%lu, size=%lu, 0%o).",
					(unsigned long) memKey, (unsigned long) size,
					IPC_CREAT | IPC_EXCL | IPCProtection),
				 (errno == EINVAL) ?
				 errhint("This error usually means that PostgreSQL's request for a shared memory "
		  "segment exceeded your kernel's SHMMAX parameter.  You can either "
						 "reduce the request size or reconfigure the kernel with larger SHMMAX.  "
				  "To reduce the request size (currently %lu bytes), reduce "
			   "PostgreSQL's shared_buffers parameter (currently %d) and/or "
						 "its max_connections parameter (currently %d).\n"
						 "If the request size is already small, it's possible that it is less than "
						 "your kernel's SHMMIN parameter, in which case raising the request size or "
						 "reconfiguring SHMMIN is called for.\n"
		"The PostgreSQL documentation contains more information about shared "
						 "memory configuration.",
						 (unsigned long) size, NBuffers, MaxBackends) : 0,
				 (errno == ENOMEM) ?
				 errhint("This error usually means that PostgreSQL's request for a shared "
				   "memory segment exceeded available memory or swap space, "
						 "or exceeded your kernel's SHMALL parameter.  You can either "
						 "reduce the request size or reconfigure the kernel with larger SHMALL.  "
				  "To reduce the request size (currently %lu bytes), reduce "
			   "PostgreSQL's shared_buffers parameter (currently %d) and/or "
						 "its max_connections parameter (currently %d).\n"
		"The PostgreSQL documentation contains more information about shared "
						 "memory configuration.",
						 (unsigned long) size, NBuffers, MaxBackends) : 0,
				 (errno == ENOSPC) ?
				 errhint("This error does *not* mean that you have run out of disk space. "
						 "It occurs either if all available shared memory IDs have been taken, "
						 "in which case you need to raise the SHMMNI parameter in your kernel, "
		  "or because the system's overall limit for shared memory has been "
				 "reached.  If you cannot increase the shared memory limit, "
		  "reduce PostgreSQL's shared memory request (currently %lu bytes), "
			"by reducing its shared_buffers parameter (currently %d) and/or "
						 "its max_connections parameter (currently %d).\n"
		"The PostgreSQL documentation contains more information about shared "
						 "memory configuration.",
						 (unsigned long) size, NBuffers, MaxBackends) : 0));
	}

	/* Register on-exit routine to delete the new segment */
	on_shmem_exit(IpcMemoryDelete, Int32GetDatum(shmid));

	/* OK, should be able to attach to the segment */
	memAddress = shmat(shmid, NULL, PG_SHMAT_FLAGS);

	if (memAddress == (void *) -1)
		elog(FATAL, "shmat(id=%d) failed: %m", shmid);

	/* Register on-exit routine to detach new segment before deleting */
	on_shmem_exit(IpcMemoryDetach, PointerGetDatum(memAddress));

	/*
	 * Append record key and ID in lockfile for data directory. Format
	 * to try to keep it the same length.
	 */
	{
		char line[32];

		sprintf(line, "%9lu %9lu\n", (unsigned long) memKey,
									 (unsigned long) shmid);
		AddToLockFile(LOCK_FILE_LINES, line);
	}

	return memAddress;
}
Beispiel #24
0
int main(int argc, char *argv[])
{
    int value = 0;

    key_t key = ftok(".", 0xFF);
    int sem_id = semget(key, 1, IPC_CREAT|0644);
    if(-1 == sem_id)
    {
        perror("semget");
        exit(EXIT_FAILURE);
    }

    if(-1 == (semctl(sem_id, 0, SETVAL, value)))
    {
        perror("semctl");
        exit(EXIT_FAILURE);
    }

    //creat the shared memory(1K bytes)
    int shm_id = shmget(key, 1024, IPC_CREAT|0644);
    if(-1 == shm_id)
    {
        perror("shmget");
        exit(EXIT_FAILURE);
    }

    //attach the shm_id to this process
    char *shm_ptr = (char*)shmat(shm_id, NULL, 0);
    if(NULL == shm_ptr)
    {
        perror("shmat");
        exit(EXIT_FAILURE);
    }

    struct sembuf sem_b;
    sem_b.sem_num = 0;      //first sem(index=0)
    sem_b.sem_flg = SEM_UNDO;
    sem_b.sem_op = -1;       //decrease 1,make sem=0
    
    printf("\nMessage receiver is running:\n");
    while(1)
    {
        if(1 == (value = semctl(sem_id, 0, GETVAL)))
        {
            printf("\tThe message is : %s\n", shm_ptr);

            if(-1 == semop(sem_id, &sem_b, 1))
            {
                perror("semop");
                exit(EXIT_FAILURE);
            }
        }

        if(0 == (strcmp(shm_ptr ,"exit")))
        {
            printf("\nExit receiver process now!\n");
            break;
        }
    }

    shmdt(shm_ptr);
    //delete the shared memory
    if(-1 == shmctl(shm_id, IPC_RMID, NULL))
    {
        perror("shmctl");
        exit(EXIT_FAILURE);
    }

    //delete the semaphore
    if(-1 == semctl(sem_id, 0, IPC_RMID))
    {
        perror("semctl");
        exit(EXIT_FAILURE);
    }

    return 0;
}
int create_shm(key_t key, const char *txt, const char *etxt, int flags) {
  int shm_id = shmget(key, SIZE, flags | PERM);
  handle_error(shm_id, etxt, PROCESS_EXIT);
  return shm_id;
}
Beispiel #26
0
int main(int argc,char* argv[]){

	if(argc>1){

		if(strcmp(argv[1],"-h")==0){

			help(argv[0]);
		}

		exit(EXIT_SUCCESS);
	}

  	struct shared_use_st *shared_stuff;
  	void *shared_memory = (void *)0;

    int shmid=0;
    sem_t * sem_id;
    pid_t child;


    sem_id=sem_open("mysemaph", O_CREAT, 0600, 1);

    if(sem_id == SEM_FAILED) {
        perror("parent sem_open");
        return;
    }

    shmid = shmget( (key_t)1234,sizeof(struct shared_use_st),0666 |IPC_CREAT );


    if(shmid==-1){

    	perror("shmget: shmget failed"); 
    	exit(EXIT_FAILURE);
    }

    shared_memory = shmat(shmid,(void *)0, 0);


    if (shared_memory == (void *)-1) {

		perror("shmat failed");
		exit(EXIT_FAILURE);
	}

	shared_stuff = (struct shared_use_st *)shared_memory;
	
    sem_wait(sem_id);
    shared_stuff->noOfProcess++;
    sem_post(sem_id);

    if((child=fork())==-1){

		perror("fork error");
		exit(EXIT_FAILURE);

	}
	else if(child==0){

		readFromShared(shared_stuff,sem_id);
		
	}
	else{

			writeToShared(shared_stuff,sem_id);
			kill(child,SIGKILL);

	}

	sem_wait(sem_id);
	shared_stuff->noOfProcess--;
	int num_process=shared_stuff->noOfProcess;
	sem_post(sem_id);

	if (shmdt(shared_memory) == -1)
	{
			perror("shmdt failed");
			exit(EXIT_FAILURE);
	}


	if(num_process==0){

		if (shmctl(shmid, IPC_RMID, 0) == -1)
		{
			perror("shmctl error");
			exit(EXIT_FAILURE);
		}
	}
	
	exit(EXIT_SUCCESS);

}
Beispiel #27
0
int main(int o_argc, const string const* o_argv) {
  string _path = getExecPath(*o_argv);
  key_t _key = ftok(_path, 'x');
  asserts(_key, "ftok");
  free(_path);
  _path = NULL;

  union  semun  _arg  ;
  struct sembuf _buf  ;
  int           _shmid;
  MyData        _data ;
  size_t        _off  ;
  
  /* Nowaday, memory is so cheap that I just do not care about the unused memory.
   * If is it too waste, then just compile with DYN_SEG_SIZE switch.
  **/
  #ifndef DYN_SEG_SIZE
  const off_t SEG_SIZE = sizeof(mydata_t);
  #endif /* DYN_SEG_SIZE */
  
  _buf.sem_num = 0;
  _buf.sem_flg = 0;

  /* Try to create a set of semaphores. */
  int _semid = semget(_key, 1, IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
  
  if(_semid == -1) {
    const int MAX_TRIES = 6;
    
    /* If semget failed, and the set does not exist then exit */
    if(errno != EEXIST) asserts(_semid, "semget");
    
    _semid = semget(_key, 1, S_IRUSR | S_IWUSR);
    asserts(_semid);
    
    struct semid_ds _ds;
    
    _arg.buf = &_ds;
    
    for(size_t i = 0; i < MAX_TRIES; i++) {
      asserts( semctl(_semid, 0, IPC_STAT, _arg) );
      if(_ds.sem_otime != 0) break;
      sleep(5);
    }
    
    if(_ds.sem_otime == 0)
      fatal (
        "The set of semaphores already exists, but it is not initialized.\n"
        "This is a permanent error, and I have given up."
      )
    ;
  }
  
  /* init semaphore */
  else {
  
    /* Note:
     *   Some systems, like Linux, implicitly initializes a set of semaphores by value 0,
     *   but unfortunately some does not. For that reason, this operation is necessary to ensure
     *   a portability.
    **/
    _arg.val = 0;
    asserts( semctl(_semid, 0, SETVAL, _arg) );
    
    /* post semaphore */
    _buf.sem_op = 1;
    asserts( semop(_semid, &_buf, 1) );
  }
  
  
  /* lock the semaphore */  
  _buf.sem_op = -1;
  asserts( semop(_semid, &_buf, 1) );
  
  /* Critical section: */ 
  
  /* there is no arguments so print shared memory object content */
  if(o_argc == 1) {
  
  
    /* obtain the descriptor of shared memory object */
    asserts( _shmid = shmget(_key, 0, S_IRUSR | S_IWUSR | SHM_RDONLY) );
    
    /* map shared memory object into virtual address space */
    assertv(_data = shmat(_shmid, NULL, 0), cast(void*)-1);

    /* read from shared memory object */
    _off = 0;
    for(size_t i = 0; i < _data->len; i++) {
      print(_data->vals + _off);
      print(" ");
      _off += strlen(_data->vals + _off) + 1;
    }
    
    println("");
  }
  
  /* write arguments in the reveres order into shared memory object */
  else {
  
    #if (defined ALLOW_CLEANUP || defined DYN_SEG_SIZE)
    struct shmid_ds _shmds;
    #endif /* ALLOW_CLEANUP || DYN_SEG_SIZE */
    
    #ifdef ALLOW_CLEANUP
    union semun _semun;
    
    /* if shared memory object already exist obtain its id and destroy, otherwise do nothing */
    if( o_argc == 2 && !strcmp(o_argv[1], "cleanup") ) {
      _shmid = shmget(_key, 0, S_IRUSR | S_IWUSR);  
      if(_shmid == -1) {
        if(errno != ENOENT) asserts(_shmid);
      }
      else asserts( shmctl(_shmid, IPC_RMID, &_shmds) );
      
      /* destroy the semaphore before exit */
      asserts( semctl(_semid, 0, IPC_RMID, _semun) );
      exit(EXIT_SUCCESS);
    } 
    #endif /* ALLOW_CLEANUP */
    
    /* use existing shared memory object or create the new one */
    #ifdef DYN_SEG_SIZE  
    off_t _segSz = sizeof(size_t);
    for(size_t i = 1; i < o_argc; i++) {
      _segSz += strlen(o_argv[i]) + 1;
    }

    /* Try to create a new shared memory object.
     * If such object already exits the destoy it before.
    **/
    _shmid = shmget(_key, _segSz, S_IRUSR | S_IWUSR | IPC_CREAT | IPC_EXCL);
    if(_shmid == -1) {
      if(errno == EEXIST) {
        asserts( _shmid = shmget(_key, 0, S_IRUSR | S_IWUSR) );
        asserts( shmctl(_shmid, IPC_RMID, &_shmds) );
        asserts( _shmid = shmget(_key, _segSz, S_IRUSR | S_IWUSR | IPC_CREAT) );
      }
    }
    #else
    asserts( _shmid = shmget(_key, SEG_SIZE, S_IRUSR | S_IWUSR | IPC_CREAT) );
    #endif /* DYN_SEG_SIZE */

    /* map shared memory object into virtual address space */
    assertv(_data = shmat(_shmid, NULL, 0), cast(void*)-1);
    
    /* write into the shared memory object */
    _data->len = o_argc - 1;
    _off = 0;
    for(size_t i = o_argc - 1; i > 0; i--) {
      /* it is safe to use strcpy, because we got enought memory */
      strcpy(_data->vals + _off, o_argv[i]);
      _off += strlen(o_argv[i]) + 1;
    }
  }
   
  /* unmap shared memory object from virtual address space */
  assertz( shmdt(_data) );
  _data = NULL;
  
  /* unlock the semaphore */
  _buf.sem_op = 1;
  asserts( semop(_semid, &_buf, 1) );

  exit(EXIT_SUCCESS);
}
Beispiel #28
0
int main()
{
	char	*cp=NULL;
	int	pid, pid1, shmid;
	int	status;
	
	key = (key_t)getpid() ;

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

	pid = fork();
	switch (pid) {
	case -1:
		tst_resm(TBROK,"fork failed");
                tst_exit() ;
	case 0:
		child();
	}

/*------------------------------------------------------*/


	if ((shmid = shmget(key, SIZE, IPC_CREAT|0666)) < 0) {
		perror("shmget");
		tst_resm(TFAIL,"Error: shmget: shmid = %d, errno = %d\n",
		shmid, errno) ;
		/*
		 * kill the child if parent failed to do the attach
		 */
		(void)kill(pid, SIGINT);
	}
	else {
#ifdef __ia64__
		  cp = (char *) shmat(shmid, ADDR_IA, 0);
#elif defined(__ARM_ARCH_4T__)
		  cp = (char *) shmat(shmid, (void*) NULL, 0);
#elif defined(__mips__)
		  cp = (char *) shmat(shmid, ADDR_MIPS, 0);
#else
		  cp = (char *) shmat(shmid, ADDR, 0);
#endif	
		if (cp == (char *)-1) {
			perror("shmat") ;
			tst_resm(TFAIL,
			"Error: shmat: shmid = %d, errno = %d\n",
			shmid, errno) ;

		/* kill the child if parent failed to do the attch */

			kill(pid, SIGINT) ;   

		/* remove shared memory segment */

			rm_shm(shmid) ;  

			tst_exit() ;
		} 
		*cp 	= 'A';
		*(cp+1) = 'B';
		*(cp+2) = 'C';

		kill(pid, SIGUSR1);
		while ( (pid1 = wait(&status)) < 0 && 
			(errno == EINTR) ) ;
		if (pid1 != pid) {
			tst_resm(TFAIL,"Waited on the wrong child") ;
			tst_resm(TFAIL,
			"Error: wait_status = %d, pid1= %d\n", status, pid1) ;
		}
	}

	tst_resm(TPASS,"shmget,shmat");

/*---------------------------------------------------------------*/


	if (shmdt(cp) < 0) {
		tst_resm(TFAIL,"shmdt");
	}

	tst_resm(TPASS,"shmdt");

/*-------------------------------------------------------------*/

	rm_shm(shmid) ;
	tst_exit() ;

/*-----------------------------------------------------------*/
	return(0);
}
Beispiel #29
0
static void getMyXImage(void)
{
#ifdef HAVE_SHM
    if (mLocalDisplay && XShmQueryExtension(mDisplay))
        Shmem_Flag = 1;
    else
    {
        Shmem_Flag = 0;
        mp_msg(MSGT_VO, MSGL_WARN,
               "Shared memory not supported\nReverting to normal Xlib\n");
    }
    if (Shmem_Flag)
        CompletionType = XShmGetEventBase(mDisplay) + ShmCompletion;

    if (Shmem_Flag)
    {
        myximage =
            XShmCreateImage(mDisplay, vinfo.visual, depth, ZPixmap, NULL,
                            &Shminfo[0], image_width, image_height);
        if (myximage == NULL)
        {
            mp_msg(MSGT_VO, MSGL_WARN,
                   "Shared memory error,disabling ( Ximage error )\n");
            goto shmemerror;
        }
        Shminfo[0].shmid = shmget(IPC_PRIVATE,
                                  myximage->bytes_per_line *
                                  myximage->height, IPC_CREAT | 0777);
        if (Shminfo[0].shmid < 0)
        {
            XDestroyImage(myximage);
            mp_msg(MSGT_VO, MSGL_V, "%s\n", strerror(errno));
            //perror( strerror( errno ) );
            mp_msg(MSGT_VO, MSGL_WARN,
                   "Shared memory error,disabling ( seg id error )\n");
            goto shmemerror;
        }
        Shminfo[0].shmaddr = (char *) shmat(Shminfo[0].shmid, 0, 0);

        if (Shminfo[0].shmaddr == ((char *) -1))
        {
            XDestroyImage(myximage);
            if (Shminfo[0].shmaddr != ((char *) -1))
                shmdt(Shminfo[0].shmaddr);
            mp_msg(MSGT_VO, MSGL_WARN,
                   "Shared memory error,disabling ( address error )\n");
            goto shmemerror;
        }
        myximage->data = Shminfo[0].shmaddr;
        ImageData = (unsigned char *) myximage->data;
        Shminfo[0].readOnly = False;
        XShmAttach(mDisplay, &Shminfo[0]);

        XSync(mDisplay, False);

        if (gXErrorFlag)
        {
            XDestroyImage(myximage);
            shmdt(Shminfo[0].shmaddr);
            mp_msg(MSGT_VO, MSGL_WARN, "Shared memory error,disabling.\n");
            gXErrorFlag = 0;
            goto shmemerror;
        } else
            shmctl(Shminfo[0].shmid, IPC_RMID, 0);

        {
            static int firstTime = 1;

            if (firstTime)
            {
                mp_msg(MSGT_VO, MSGL_V, "Sharing memory.\n");
                firstTime = 0;
            }
        }
    } else
    {
      shmemerror:
        Shmem_Flag = 0;
#endif
        myximage = XCreateImage(mDisplay, vinfo.visual, depth, ZPixmap,
                             0, NULL, image_width, image_height, 8, 0);
        ImageDataOrig = malloc(myximage->bytes_per_line * image_height + 32);
        myximage->data = ImageDataOrig + 16 - ((long)ImageDataOrig & 15);
        memset(myximage->data, 0, myximage->bytes_per_line * image_height);
        ImageData = myximage->data;
#ifdef HAVE_SHM
    }
#endif
}
Beispiel #30
0
int main(int argc, char* argv[])
{
	int shmid ;
	char line[128];
	int fd_s, fd_r ;

	//open fifo  12.fifp 21.fifo
	fd_s = open("./12.fifo", O_WRONLY);

	fd_r = open("./21.fifo", O_RDONLY);

	printf("fd_s: %d, fd_r: %d\n", fd_s, fd_r);

	//shm
	shmid = shmget((key_t)1234, sizeof(mem_t), IPC_CREAT|0666);
	if(shmid == -1)
	{
		perror("shmget");
		exit(1);
	}
	pmem_t pm = (pmem_t)shmat(shmid, NULL, 0);

	if((void*)pm == (void*)-1)
	{
		perror("shmat");
		exit(1);
	}
	pm ->m_lock = 1 ;

	pm ->m_unshow = 0 ;


	//select
	fd_set rds ;
	struct timeval tm ;
	int ret ;
	while(1)
	{
		FD_ZERO(&rds);

		FD_SET(0, &rds);

		FD_SET(fd_r, &rds);

		tm.tv_usec = 0 ;
		tm.tv_sec = 5;

		ret = select(1024, &rds, NULL, NULL, &tm);

		if(ret == 0)
		{
			continue ;
		}else if(ret > 0)
		{
			if(FD_ISSET(0, &rds))
			{
				memset(line, 0, 128);
				read(0, line, 127);
				write(fd_s, line, strlen(line));
			}
			if(FD_ISSET(fd_r, &rds ))
			{
				memset(line, 0, 128);
				read(fd_r, line, 127);

				Lock(pm);
				while( pm -> m_unshow == 1)
				{
					unLock(pm);
					sleep(1);

					Lock(pm);
				}

				strcpy(pm ->m_buf, line);

				pm ->m_unshow = 1 ;

				unLock(pm);
			}
		}





	}


	close(fd_s);
	close(fd_r);
	shmdt(pm);

	shmctl(shmid, IPC_RMID, NULL);


	return 0 ;
}