posix IPC shared_memory一例

 
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
int value = 5;
int main(void)
{
 pid_t pid;
 pid = fork();
 if (pid == 0)
 {
     value += 15;
 }
 else if (pid > 0)
 {
     wait(NULL);
     printf("PARENT: value = %d", value);
     exit(0);
 }
}


输出PARENT: value =  5                 //              (各个进程有独立存储空间)

通过shared_memory解决数据共享 实现进程间通讯 代码稍作修改如下:

#include <sys/types.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
int value = 5;
int main(void)
{
 pid_t pid;
 int segment_id;
 char* shared_memory;
 const int size = 4096;
 
 segment_id = shmget(IPC_PRIVATE, size,  S_IRUSR|S_IWUSR);
 shared_memory = (char*)shmat(segment_id, NULL, 0);
 pid = fork();
 if (pid == 0)
 {
     value += 15;
     sprintf(shared_memory, "%d", value);
 }
 else if (pid > 0)
 {
     wait(NULL);
     printf("PARENT: value = %s\n", shared_memory);
     exit(0);
 }
 return 0;
}


输出PARENT: value =  20   

 

你可能感兴趣的:(null,存储,include,通讯)