zoukankan      html  css  js  c++  java
  • linux:共享内存

    #include <sys/ipc.h>
    #include <sys/shm.h>
    #include <string.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <iostream>
    using namespace std;
    struct shared_use_st
    {
    	int flags;
    	char buff[1000];
    };
    int main()
    {
    	void *shared_memory = NULL;
    	int shmid = shmget((key_t)1234,sizeof(shared_use_st),0666|IPC_CREAT);
    	if(shmid==-1)
    	{
    		fprintf(stderr,"shmget failed
    ");
    		exit(0);
    	}
    	
    	shared_memory = shmat(shmid,(void *)0,0);
    	if(shared_memory==(void *)-1)
    	{
    		printf("Error");
    		exit(0);
    	}
    	printf("Memory attached at %x
    ",(int)shared_memory);
    	
    	shared_use_st *shared_buff = (shared_use_st*)shared_memory;
    	shared_buff->flags = 0;
    	if(fork()==0)
    	{
    		while(1)
    		{
    		 while(shared_buff->flags==0)
    		 {
    			strncpy(shared_buff->buff,"liuhuiyan",10);
    			shared_buff->flags = 1;
    			sleep(1);
    		 }
    		}		
    	}
    	else
    	{
    		while(1)
    		{
    			while(shared_buff->flags==1)
    			{
    				char data_buff[100];
    				strcpy(data_buff,shared_buff->buff);
    				cout<<data_buff<<endl;
    				shared_buff->flags=0;	
    			}
    		}
    	}
    	shmdt(shared_memory);
    	return 0;
    }

  • 相关阅读:
    P6585 中子衰变
    [APIO2020]有趣的旅途
    CF1354F Summoning Minions
    CF1361C Johnny and Megan's Necklace
    CF1368E Ski Accidents
    CF1458C Latin Square
    CF1368F Lamps on a Circle
    用户和组的管理
    Windows命令
    1
  • 原文地址:https://www.cnblogs.com/yangykaifa/p/7090311.html
Copyright © 2011-2022 走看看