共享内存: 1、在内核
中创建共享内存; 2、进程1和进程2都能够访问到,通过这段内存空间进行数据传递; 3、共享内存是所有进程间通信方式中
,效率最高
,不需要在内核中往返进行拷贝
; 4、共享内存的内存空间大小是4KB的整数倍
; 常用的接口函数: 一、创建共享内存(shmget函数):
# include <sys/ipc.h>
# include <sys/shm.h>
int shmget ( key_t key, size_t size, int shmflg) ;
二、映射共享内存到当前的进程空间(shmat函数):
# include <sys/ipc.h>
# include <sys/shm.h>
void * shmat ( int shmid, const void * shmaddr, int shmflg) ;
# include <sys/ipc.h>
# include <sys/shm.h>
int shmdt ( const void * shmaddr) ;
# include <sys/ipc.h>
# include <sys/shm.h>
int shmctl ( int shmid, int cmd, struct shmid_ds * buf) ;
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include <sys/types.h>
# include <sys/ipc.h>
# include <sys/shm.h>
# include <unistd.h>
# define PIGE_SIZE 4 * 1024
int main ( int argc, char const * argv[ ] )
{
key_t key = ftok ( "/home/linux/work/MSG" , 'k' ) ;
if ( - 1 == key)
{
perror ( "ftok error" ) ;
exit ( 1 ) ;
}
int shmid = shmget ( key, 2 * PIGE_SIZE, IPC_CREAT| 0666 ) ;
if ( - 1 == shmid) \
{
perror ( "shmget error" ) ;
exit ( 1 ) ;
}
char * sh_addr = ( char * ) shmat ( shmid, NULL , 0 ) ;
if ( ( void * ) - 1 == sh_addr)
{
perror ( "shmat error" ) ;
exit ( 1 ) ;
}
while ( 1 )
{
fgets ( sh_addr, 128 , stdin ) ;
sh_addr[ strlen ( sh_addr) - 1 ] = '\0' ;
if ( ! strncmp ( sh_addr, "quit" , 4 ) )
{
break ;
}
}
if ( - 1 == shmdt ( sh_addr) )
{
perror ( "shmdt error" ) ;
exit ( 1 ) ;
}
if ( - 1 == shmctl ( shmid, IPC_RMID, NULL ) )
{
perror ( "shmctl error" ) ;
exit ( 1 ) ;
}
return 0 ;
}
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include <sys/types.h>
# include <sys/ipc.h>
# include <sys/shm.h>
# include <unistd.h>
# define PIGE_SIZE 4 * 1024
int main ( int argc, char const * argv[ ] )
{
key_t key = ftok ( "/home/linux/work/MSG" , 'k' ) ;
if ( - 1 == key)
{
perror ( "ftok error" ) ;
exit ( 1 ) ;
}
int shmid = shmget ( key, 2 * PIGE_SIZE, IPC_CREAT| 0666 ) ;
if ( - 1 == shmid) \
{
perror ( "shmget error" ) ;
exit ( 1 ) ;
}
char * sh_addr = ( char * ) shmat ( shmid, NULL , 0 ) ;
if ( ( void * ) - 1 == sh_addr)
{
perror ( "shmat error" ) ;
exit ( 1 ) ;
}
while ( 1 )
{
sleep ( 2 ) ;
printf ( "%s\n" , sh_addr) ;
if ( ! strncmp ( sh_addr, "quit" , 4 ) )
{
break ;
}
}
if ( - 1 == shmdt ( sh_addr) )
{
perror ( "shmdt error" ) ;
exit ( 1 ) ;
}
if ( - 1 == shmctl ( shmid, IPC_RMID, NULL ) )
{
perror ( "shmctl error" ) ;
exit ( 1 ) ;
}
return 0 ;
}
linux@ubuntu: ~ / work/ MSG$ gcc w3. c - o w3
linux@ubuntu: ~ / work/ MSG$ . / w3
hi
hello
china
quit
linux@ubuntu: ~ / work/ MSG$ gcc r3. c - o r3
linux@ubuntu: ~ / work/ MSG$ . / r3
hi
hi
hi
hello
china
china
china
quit
shmctl error: Invalid argument
注意: 不按4k的整数倍给shmget传参
,分配时也是按4k的整数倍分配
;