發送端: 申請共享內存區域並寫入數據到共享內存區域
sender.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/shm.h> #define BUFSIZ 102400 int main() { int shmid=-1; char * viraddr; char buffer[BUFSIZ]; key_t shmkey =<SPAN style="COLOR: #ff0000"> ftok("/home/cip/test/", 0);</SPAN> shmid = shmget(shmkey,BUFSIZ, IPC_CREAT|0666); //申請共享區域 viraddr=(char*)shmat(shmid,0,0); //附件共享地址到將本進程 while(1) { puts("enter some text:"); fgets(buffer, BUFSIZ, stdin); strcat(viraddr,buffer);添加數據到共享內存中 if(strncmp(buffer,"end",3)==0) { break; } } shmdt(viraddr); //撤銷地址映射 return 0; } #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/shm.h> #define BUFSIZ 102400 int main() { int shmid=-1; char * viraddr; char buffer[BUFSIZ]; key_t shmkey = ftok("/home/cip/test/", 0); shmid = shmget(shmkey,BUFSIZ, IPC_CREAT|0666); //申請共享區域 viraddr=(char*)shmat(shmid,0,0); //附件共享地址到將本進程 while(1) { puts("enter some text:"); fgets(buffer, BUFSIZ, stdin); strcat(viraddr,buffer);添加數據到共享內存中 if(strncmp(buffer,"end",3)==0) { break; } } shmdt(viraddr); //撤銷地址映射 return 0; } gcc -o send sender.c
接收端:
讀取共享區的內容
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/shm.h> #define BUFSIZ 102400 int main() { int shmid=-1; char * viraddr; char buffer[BUFSIZ]; key_t shmkey = ftok<SPAN style="COLOR: #ff0000">("/home/cip/test/", 0);</SPAN> shmid = shmget(shmkey,BUFSIZ, IPC_CREAT|0666); //獲取共享區域 viraddr=(char*)shmat(shmid,0,0); printf("Your message is:\n%s", viraddr); shmdt(viraddr); shmctl(shmid, IPC_RMID,0); return 0; } #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/shm.h> #define BUFSIZ 102400 int main() { int shmid=-1; char * viraddr; char buffer[BUFSIZ]; key_t shmkey = ftok("/home/cip/test/", 0); shmid = shmget(shmkey,BUFSIZ, IPC_CREAT|0666); //獲取共享區域 viraddr=(char*)shmat(shmid,0,0); printf("Your message is:\n%s", viraddr); shmdt(viraddr); shmctl(shmid, IPC_RMID,0); return 0; }