Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*******************************************
- * Author : Diego Cordoba / @d1cor *
- * Purpose : juncotic.com / um.edu.ar *
- *******************************************/
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/ipc.h>
- #include <sys/shm.h>
- #include <time.h>
- #include <string.h>
- #include <errno.h>
- #include <getopt.h>
- #include <sys/stat.h>
- #include <sys/mman.h>
- #include <sys/types.h>
- #include <fcntl.h> /* For O_* constants */
- #define MEMSIZE 512
- const char *progname;
- char *shm_abre_y_mapea (size_t size, mode_t mode){
- static int shm_id=0;
- char *ptr;
- // creates shm segment on main memory
- shm_id = shm_open("/test", O_CREAT | O_RDWR, mode);
- fprintf (stderr,"Usando shm_id=%d\n", shm_id);
- if (shm_id < 0) return NULL;
- // grow segment to a fixed size
- ftruncate(shm_id, size);
- // map segment into a private memory space in the process
- ptr = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_id, 0);
- return ptr;
- }
- void usage (FILE * f, int exit_status){
- fprintf (f, "ERROR: uso %s {-r | -w | -d }\n", progname);
- exit (exit_status);
- }
- int main (int argc, char * const argv[]){
- int c, opt_read=0, opt_write=0, count=0;
- char * ptr=NULL;
- const char * ouch=NULL;
- progname=argv[0];
- while((c=getopt(argc, argv, "rwd"))!=-1){
- switch (c){
- case 'r': opt_read++; break;
- case 'w': opt_write++; break;
- case 'd': shm_unlink("test"); return 0;
- default: usage(stderr, 255); break;
- }
- }
- if (!(opt_read^opt_write))usage(stderr, 255);
- //crea y asigna la memoria a ptr
- ptr = shm_abre_y_mapea(MEMSIZE, 0666);
- if (!ptr){
- ouch="Obtener memoria compartida";
- goto err;
- }
- if (opt_write){
- int resto=MEMSIZE-1;
- fprintf (stdout, "Leyendo del stdin .....resto\n");
- //leo del stdin y lo asigno al segmento de memoria compartida
- while ((count=read(STDIN_FILENO, ptr, resto))>0){
- resto-=count;
- if(resto<0){
- fprintf (stderr, "Se acabó el espacio\n");
- break;
- }
- ptr+=count;
- }
- if (count<0){
- ouch="read()";
- goto err;
- }
- ptr [count]=0;//asigno el caracter nulo al final del segmento
- }
- else if (opt_read){
- fprintf (stdout, "Escribiendo en stdout......\n");
- printf (ptr); //escribe el el stderr el contenido de la memoria
- }
- return 0;
- err:
- fprintf (stderr, "Error: %s :%s\n", ouch, strerror(errno));
- return 1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement