GNU/Linux >> Linux Esercitazione >  >> Linux

Come utilizzare la memoria condivisa con Linux in C

Ecco un esempio per la memoria condivisa :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define SHM_SIZE 1024  /* make it a 1K shared memory segment */

int main(int argc, char *argv[])
{
    key_t key;
    int shmid;
    char *data;
    int mode;

    if (argc > 2) {
        fprintf(stderr, "usage: shmdemo [data_to_write]\n");
        exit(1);
    }

    /* make the key: */
    if ((key = ftok("hello.txt", 'R')) == -1) /*Here the file must exist */ 
{
        perror("ftok");
        exit(1);
    }

    /*  create the segment: */
    if ((shmid = shmget(key, SHM_SIZE, 0644 | IPC_CREAT)) == -1) {
        perror("shmget");
        exit(1);
    }

    /* attach to the segment to get a pointer to it: */
    if ((data = shmat(shmid, NULL, 0)) == (void *)-1) {
        perror("shmat");
        exit(1);
    }

    /* read or modify the segment, based on the command line: */
    if (argc == 2) {
        printf("writing to segment: \"%s\"\n", argv[1]);
        strncpy(data, argv[1], SHM_SIZE);
    } else
        printf("segment contains: \"%s\"\n", data);

    /* detach from the segment: */
    if (shmdt(data) == -1) {
        perror("shmdt");
        exit(1);
    }

    return 0;
}

Passaggi :

  1. Usa ftok per convertire un percorso e un identificatore di progetto in una chiave IPC System V

  2. Usa shmget che alloca un segmento di memoria condivisa

  3. Usa shmat per allegare il segmento di memoria condivisa identificato da shmid allo spazio degli indirizzi del processo chiamante

  4. Eseguire le operazioni nell'area di memoria

  5. Stacca usando shmdt


Ci sono due approcci:shmget e mmap . Parlerò di mmap , poiché è più moderno e flessibile, ma puoi dare un'occhiata a man shmget (o questo tutorial) se preferisci utilizzare gli strumenti vecchio stile.

Il mmap() La funzione può essere utilizzata per allocare buffer di memoria con parametri altamente personalizzabili per controllare l'accesso e le autorizzazioni e per supportarli con l'archiviazione del file system, se necessario.

La seguente funzione crea un buffer in memoria che un processo può condividere con i suoi figli:

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>

void* create_shared_memory(size_t size) {
  // Our memory buffer will be readable and writable:
  int protection = PROT_READ | PROT_WRITE;

  // The buffer will be shared (meaning other processes can access it), but
  // anonymous (meaning third-party processes cannot obtain an address for it),
  // so only this process and its children will be able to use it:
  int visibility = MAP_SHARED | MAP_ANONYMOUS;

  // The remaining parameters to `mmap()` are not important for this use case,
  // but the manpage for `mmap` explains their purpose.
  return mmap(NULL, size, protection, visibility, -1, 0);
}

Di seguito è riportato un programma di esempio che utilizza la funzione definita sopra per allocare un buffer. Il processo genitore scriverà un messaggio, eseguirà il fork e quindi attenderà che il suo figlio modifichi il buffer. Entrambi i processi possono leggere e scrivere la memoria condivisa.

#include <string.h>
#include <unistd.h>

int main() {
  char parent_message[] = "hello";  // parent process will write this message
  char child_message[] = "goodbye"; // child process will then write this one

  void* shmem = create_shared_memory(128);

  memcpy(shmem, parent_message, sizeof(parent_message));

  int pid = fork();

  if (pid == 0) {
    printf("Child read: %s\n", shmem);
    memcpy(shmem, child_message, sizeof(child_message));
    printf("Child wrote: %s\n", shmem);

  } else {
    printf("Parent read: %s\n", shmem);
    sleep(1);
    printf("After 1s, parent read: %s\n", shmem);
  }
}

Linux
  1. Come uso Vagrant con libvirt

  2. Come usare BusyBox su Linux

  3. Come uso cron in Linux

  4. Come usare il comando Su in Linux

  5. Comando SCP in Linux:come usarlo, con esempi

Come utilizzare il comando who in Linux con esempi

Comando alias Linux:come usarlo con esempi

Come controllare la memoria condivisa di Linux usando il comando ipcs

Come utilizzare il comando gunzip di Linux con esempi

Come utilizzare il comando Linux rm con esempi

Come utilizzare il comando Sleep in Linux:spiegato con esempi