Ejemplo n.º 1
0
int main()
{
     char *shm;
     int shmid;
     int producer, consumer, i;
     consumer=open_semaphore_set(ftok("consumer",0),1);
     init_a_semaphore(consumer,0,1);
     producer=open_semaphore_set(ftok("producer",0),1);
     init_a_semaphore(producer,0,1);
   //  shm=(struct exchange *)shminit(ftok("shared",0));
     if((shmid=shmget(ftok("shared",0),SHMSZ, 0666|IPC_CREAT))==-1)
     { 
          printf("shmget failed.\n");
          exit(1);
     } 
    shm=shmat(shmid,(unsigned char *)0,0);
     for(i=0; ; i++)
     {
        semaphore_V(consumer);
        semaphore_P(producer);
       printf("Data receiverd: %s\n",shm);
           sleep(1);
          if(strcmp(shm,"end")==0)
               break;
       }
           semctl(producer,0,IPC_RMID,0);
          semctl(consumer,0,IPC_RMID,0);
                }
Ejemplo n.º 2
0
int main()
{
    struct exchange
    {
        char buf[BUFSIZ+80];
        int seq;
    }shm;
    int shmid;
    unsigned char *retval;
    int producer, consumer, i;
    char readbuf[BUFSIZ];

    //创建信号量consumer
    consumer = open_semaphore_set(ftok("consumer", 0), 1);

    //初始化信号量consumer的值为1
    init_a_semaphore(consumer, 0, 1);

    //创建信号量producer
    producer = open_semaphore_set(ftok("producer", 0), 1);

    //初始化信号量producer的值为1
    init_a_semaphore(producer, 0, 1);

    //创建共享存储区用于存放生产者产生的数据
    shmid = shmget(ftok("share", 0),sizeof(struct exchange), 0666|IPC_CREAT);
    retval = shmat(shmid, (unsigned char *)0, 0);

    //生产者与消费者同步
    for (i = 0; ; i++)
    {
        printf("enter some text:");
        fgets(readbuf, BUFSIZ, stdin);
        semaphore_P(consumer);
        sprintf(retval, "messge %2d form producer %d is \" %s \" ", i, getpid(), readbuf);
        semaphore_V(producer);
        if (strncmp(readbuf, "end", 3) == 0)
            break;
    }
    exit(0);

    return 0;
}
Ejemplo n.º 3
0
int main(void) /* 服務程式 */
{
    struct exchange *shm;
    int producer_ok,consumer_ok,i;
    int shmid;
    char readbuf[BUFSIZ];

    /* 建立訊號量consumer和producer */
    consumer_ok = open_semaphore_set(key1, 1);
    producer_ok= open_semaphore_set(key2, 1);
    init_a_semaphore(consumer_ok, 0, 1);  /* 禁止消費 */
    init_a_semaphore(producer_ok, 0, 0);  /* 容許生產 */

    /* 獲得並連線名為"shared"的共享儲存段 */
    shm = (struct exchange *)shminit(ftok("shared",0),&shmid);

    /* 從標准輸入讀資料並寫至共享儲存段 */
    for ( i=0; ; i++ ) {
         /* 讀入資料 */
        semaphore_P(consumer_ok);   /* 等待客戶執行緒釋放共享儲存段 */
        printf("Enter some text:");
        fgets(readbuf,BUFSIZ,stdin);
         /* 填充共享儲存緩沖 */
        shm->seq = i;
        sprintf(shm->buf, "%s",readbuf);
        semaphore_V(producer_ok);  /* 容許客戶執行緒取資料 */
        if (strncmp(readbuf, "end", 3) == 0 )
            break;
    }
    semaphore_P(consumer_ok); /* 等待客戶執行緒消費完畢 */
    /* 移除訊號量 */
    rm_semaphore(producer_ok);
    rm_semaphore(consumer_ok);

    /* 分離並移除共享儲存段 */
    shmdt(shm);
    shmctl(shmid, IPC_RMID, (struct shmid_ds *)NULL);
    exit(0);
}