天天看點

fork

#include <iostream>

#include <unistd.h>

#include <sys/wait.h>

#include <fcntl.h> // O_RDWR

#include <cstdio> // open()

#include <sys/mman.h> // mmap() munmap()

#include <semaphore.h>

#include <sstream>

using namespace std;

int main(){

   /*

   int fd = open("/dev/zero",O_RDWR);

   if(-1 == fd){

       perror("open error");

return 1;

   }

   int* p = (int*)mmap(NULL,sizeof(int),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);

   */

   sem_t* psem = sem_open("/sem.test",O_CREAT|O_RDWR,0666,1);

   int* p = (int*)mmap(NULL,sizeof(int),PROT_READ|PROT_WRITE,MAP_SHARED|MAP_ANON,-1,0);

   // int* p = (int*)malloc(sizeof(int));

   if(MAP_FAILED == p){

       perror("mmap error");

return 1;

   }

   *p = 100;

   fork();

       for(int i=0;i<50;++i){

     // --*p

     // cout << *p << endl;

     sem_wait(psem);

     // cout <<"parent " <<p<<":"<< --*p << endl;

     ostringstream oss;

     oss << getpid() << ":" << --*p << endl;

     string s = oss.str();

     write(STDOUT_FILENO,s.c_str(),s.size()+1);

     sem_post(psem);

}

// wait(NULL);  

/*    }else{

       for(int i=0;i<50;++i){

     sem_wait(psem);

     // cout <<"child " << p<<":"<< --*p << endl;

     ostringstream oss;

     oss <<"child:" << --*p << endl;

     string s = oss.str();

     write(STDOUT_FILENO,s.c_str(),s.size()+1);

     sem_post(psem);

}

   }*/

   munmap(p,sizeof(int));

   sem_close(psem);

   psem = NULL;