#include<unistd.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<errno.h>
#define KEY 1234 //鍵
#define SIZE 1024 //欲建立的共享記憶體的大小
int main(){
int shmid;
char *shmaddr;
struct shmid_ds buf;
shmid=shmget(KEY,SIZE,IPC_CREAT|0600);//建立共享記憶體
if(shmid==-1){
printf("create share memory failed: %s",strerror(errno));
return 0;
}
if(fork()==0){
shmaddr=(char *)shmat(shmid,NULL,0);//系統自動選擇一個地址連接
if(shmaddr==(void *)-1){
printf("connect to the share memory failed: %s",strerror(errno));
return 0;
}
strcpy(shmaddr,"hello,this is child process!\n");
shmdt(shmaddr); //斷開與共享記憶體的連接
return 0;
}
else
{
sleep(3); //等待子行程執行完畢
shmctl(shmid,IPC_STAT,&buf); //取得共享記憶體的相關資訊
printf(" size of the share memory:");
printf("shm_segsz=%d bytes \n",buf.shm_segsz);
printf("process id of the creator:");
printf("shm_cpid=%d\n",buf.shm_cpid);
printf("process id of the last operator:");
printf("shm_lpid=%d\n",buf.shm_lpid);
shmaddr=(char *)shmat(shmid,NULL,0);//系統自動選擇一個地址連接
if(shmaddr==(void *)-1){
printf("connect to the share memory failed: %s",strerror(errno));
return 0;
}
printf("print the content of the share memory:");
printf("%s\n",shmaddr);
shmdt(shmaddr); //斷開與共享記憶體的連接
shmctl(shmid,IPC_RMID,NULL);
//當不再有任何其他行程使用該共享記憶體時系統將自動銷毀它
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/132920.html
標籤:內核源代碼研究區
下一篇:樹莓派 紅外編碼錄制
