【代码】
申请一个共享内存区,attach到进程当中,然后通过fork创建子进程。理论上子进程和父进程是各自有在自己的内存空间,对变量的修改互不影响的,但是共享内存中的数据由子进程修改以后,父进程可以得知。
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
extern int etext,edata,end;
int main(int argc,char* argv[])
{
 int shm_size;
 int prj_id;
 key_t key;
 int shm_id;
 int pid;
 char *addr,*shm_addr;
 if(argc != 3)
 {
  printf("Usage: %s shm_size message.\n",argv[0]);
  return 1;
 }
 shm_size = atoi(argv[1]);
 //generate IPC key_word,还是从这个步骤开始。
 prj_id = 2;
 key = ftok("/home/gaolu",prj_id);
 if(-1 == key)
 {
  perror("Can't generate the IPC key.\n");
  return 1;
 }
 
 //creat sh_memory,size is argv[1]
 shm_id = shmget(key,shm_size,IPC_CREAT|0660);
 if(-1 == shm_id)
 {
  perror("Can't creat a shared memory segment.\n");
  return 1;
 }
 
 //attach到当前进程
 addr = (char*)shmat(shm_id,NULL,0);
 if(addr == (char*)(-1))
 {
  perror("Can't attech the memory to process.\n");
  return 1;
 }
 else
 {
  shm_addr = addr;
 }
 //print the information of process
 printf("==========address information==============\n");
 printf("etext address: 0x%x.\n",&etext);
 printf("edata address: 0x%x.\n",&edata);
 printf("end address: 0x%x.\n",&end);
 printf("shared memroy segment address: 0x%x.\n",shm_addr);
 printf("===========================================\n");
 strcpy(shm_addr,argv[2]);
 printf("The input message is: %s.\n",argv[2]);
 printf("Before fork,the message in shared memeroy is: %s.\n",shm_addr);
 
 //creat child process
 pid = fork();
 if(-1 == pid)
 {
  perror("Fail to creat child process.\n");
  return 1;
 }
 else if(pid == 0)
 {
  //for child process
  printf("In child process,the message is: %s.\n",shm_addr);
  printf("Now modify the message in shared memory segment.\n");
  *shm_addr+=1;
  _exit(0);
 }
 else
 {
  //for parent process
  wait(NULL);
  printf("In parent process, we can read the message in shared memory is %s.\n",shm_addr);
  
  if(shmdt(shm_addr)==-1)
  {
   perror("Fail to release the memroy.\n");
   return 1;
  }
  //delete the shared memory segment
  if(shmctl(shm_id,IPC_RMID,NULL)==-1)
  {
   perror("Can't delete the shared memory segment.\n");
   return 1;
  }
 }
 return 0;
 
}
执行结果:
gaolu@gaolu-desktop:~$ gcc -o shm systemcall2.c
gaolu@gaolu-desktop:~$
gaolu@gaolu-desktop:~$ ./shm 1024 ABCDEFG
==========address information==============
etext address: 0x80489b8.
edata address: 0x804a044.
end address: 0x804a04c.
shared memroy segment address: 0xb7f6e000.
===========================================
The input message is: ABCDEFG.
Before fork,the message in shared memeroy is: ABCDEFG.
In child process,the message is: ABCDEFG.
Now modify the message in shared memory segment.
In parent process, we can read the message in shared memory is BBCDEFG.
gaolu@gaolu-desktop:~$
gaolu@gaolu-desktop:~$
gaolu@gaolu-desktop:~$