One, shared memory
Shared memory is the most efficient way to communicate, because there is no need for a process to be copied to the kernel and another process to read in the kernel.
Second, ipcs-m View shared memory
Ipcrm-m Deleting shared memory
Three, the main function
Shmget Create
Shmctl Delete
Shmat Hook up
SHMDT Cancel Hook up
Man function Name View * * * *
Iv. implementation of the Code
Comm.h
1 #pragma once 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <unistd.h> 5 # Include<sys/ipc.h> 6 #include <sys/shm.h> 7 #define _PATH_ "." 8 #define _PROJID_ 0x666 9 #define _SHM_SIZE_ 4096 int getshmget (); one int destoryshm (int shm_id); char* at_shm (int shm_id); int Delete_shm (char *addr);
Comm.c
1 #include "comm.h" 2 int getshmget () 3 { 4 key_t key=ftok (_path_,_projid_); 5 6 int shmflg=ipc_creat |0666; 7 int Shm_id=shmget (KEY,_SHM_SIZE_,SHMFLG); 8 if (shm_id<0) 9 { perror ("Shmget"); One by one return-1; The return shm_id; destoryshm int (int shm_id) + { shmctl return (shm_id,ipc_rmid,null); char* at_shm (int shm_id) ( char*) Shmat (shm_id,null,0); Delete_shm Int (char *addr)- { shmdt return (addr); 28}
Client.c
1 #include "comm.h" 2 int main () 3 { 4 int shm_id=getshmget (); 5 Char *addr=at_shm (shm_id); 6 int i=0; 7 for (; i<_shm_size_;i++) 8 { 9 addr[i]= ' A '; Ten addr[i+1]= ' + '; sleep (1); delete_shm (addr); return 0; 15}
Server.c
1 #include "comm.h" 2 int main () 3 { 4 int shm_id=getshmget (); 5 char * ADDR=AT_SHM (shm_id); 6 int i=0; 7 for (; i<_shm_size_;i++) 8 { 9 printf ("%s\n", addr); Ten Sleep (1); One } delete_shm (addr); Destoryshm (shm_id); return 0; 15}
Run results
The above is the Linux-interprocess communication-shared memory content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!