Code:
1#include <stdio.h>2#include <stdlib.h>3#include <sys/shm.h>4 /************* basic function api********************5 Shared memory function API6 int Shmget (key_t key, int size, int flag)7 Key:8 the key value of shared memory through which multiple processes can access the same shared memory. Common special Values: ipc_private, creating private shared memory for the current process9 Size:Ten Specify the size of the shared memory creation One flag: A Operation Permissions - char * shmat (int shm_id, const void * addr, int flag) - shm_id: the the shared memory identifier to be mapped - Addr: - Specifies the address of the shared memory that is mapped in the calling process. Typically, a value of 0 indicates that an address is automatically assigned by the system. - flag: + set operation permissions for shared memory. A value of 0 indicates that the shared memory can be read and written. - int shmctl (int shm_id, int cmd, struct shmid_ds * buf) + shm_id: A Shared Memory Identifiers at cmd: - Specify the requested action: Ipc_stat ipc_set ipc_rmid shm_lock shm_unlock - BUF: - structure Body Pointer - int SHMDT (const void * addr) - **********************************************/ in #defineTest_pipe 0 - #defineTest_shmget 0 to #defineTest_at_w 0 + #defineTest_at_r 0 - #defineTest_dt 1 the intMainintargcChar*argv[]) * { $ #ifTest_pipePanax Notoginseng intx,fd[2]; - Charbuf[ -],s[ -]; the pipe (FD); +x =fork (); A if(0==x) the { +sprintf (BUF,"This was an pipe!"); -Write (fd[1],buf, -); $Exit0); $ } - Else - { theWait0); -Read (fd[0],s, -);Wuyiprintf"read:%s\n", s); the } - #endif Wu - #ifTest_shmget About intshm_id; $shm_id = Shmget (Ipc_private,4096,0666); - if(Shm_id <0) - { -Perror ("Shmget ID < 0"); AExit0); + } theprintf"successfully established shared memory area:%d\n", shm_id); -System"ipcs-m"); $ #endif the the #ifTest_at_w the intshm_id; the Char*Shm_buf; -shm_id = Atoi (argv[1]); inShm_buf = Shmat (shm_id,0,0); theprintf"write as data to shared memory: \ n"); thesprintf (Shm_buf,"read and write to shared memory! "); Aboutprintf"%s\n", shm_buf); the #endif the the #ifTest_at_r + intshm_id; - Char*Shm_buf,str; theshm_id = Atoi (argv[1]);BayiShm_buf = Shmat (shm_id,0,0); theprintf"write as data to shared memory: \ n"); the sprintf (STR,SHM_BUF); -printf"%s\n", str); -System"ipcs-m"); the #endif the the #ifTest_dt the intshm_id; - Char*Shm_buf; theshm_id = Atoi (argv[1]); theShm_buf = Shmat (shm_id,0,0); the SHMDT (SHM_BUF);94 Shmctl (shm_id,ipc_rmid,null); theSystem"ipcs-m"); the #endif the}
Not to be continued ~
Programming of C language process communication under Linux