2013-07-19 38 views
2

服务器代码下面的一个字符串转换成共享内存变量。使用信号量共享内存安全写入

客户端代码显示共享内存中可用的字符串。

全码:available in this github link

Server.c

int main(int argc, char *argv[]) 
{ 
    /* code to create posix shared memory and posix named semaphore */ 

    /* critical section start */ 

    snprintf(shared_msg->content, MAX_MSG_LENGTH, "%s", argv[1]); 

    /* critical section end */ 
} 

Client.c

int main(int argc, char *argv[]) 
{ 
    /* code to open posix shared memory and posix named semaphore */ 

    for(i=0; i<20; i++){ 
     /* critical section start */ 

     //operation of semaphore 
     while(loop < 15){ 
      printf("Type : %d, content : %s\n", shared_msg->type, shared_msg->content); 
      sleep(1); 
      loop++; 
     } 

    /* Critical section end */ 

    loop = 0; 
    printf("loop %d finished\n", i); 
     } 
} 

如何使用上面的代码(等待和后)POSIX信号,以达到以下要求

  • 客户端启动时必须显示共享内存数据。一旦内部while循环完成后,只有客户端释放共享内存。
  • 如果服务器启动并尝试将数据写入共享内存,当客户端在while循环运行时,信号量不会写入允许写入,直到客户端释放信号量。当客户端释放信号

感谢

  • 在单线服务器必须写。

  • +0

    你试过'男人sem_overview'上命令行? –

    +0

    是的。我仍然有些挣扎。 – sujin

    +0

    什么客户端服务器通过共享内存进行通信?为什么不使用管道或套筒? –

    回答

    1

    你想要一个准互斥或二进制信号量,即一次只有一个进程可以访问资源,在这种情况下,共享内存。所以,这看起来错误:

    mysem = sem_open(SEMOBJ_PATH, O_CREAT | O_EXCL | O_RDWR, S_IRWXU | S_IRWXG, 2); 
    

    你想要的初始值是1,想要写的共享内存调用sem_wait递减CTR为0,从而迫使任何其他进程调用sem_wait等到值的第一个进程是非零的。换句话说,信号量被锁定,直到持有它的进程执行sem_post

    你的伪代码看起来基本上是正确的。 sem_wait当您输入临界区域时,sem_post当您退出。根据我的理解,我认为你的问题在于错误地初始化sem_open上的信号量。

    0

    从@Duck的答案我重写代码。现在我得到预期的输出。

    我初始化旗语1 @Duck答案说

    更新server.c

    int main(int argc, char *argv[]) 
    { 
        /* code to create posix shared memory and posix named semaphore */ 
    
        /* critical section start */ 
        sem_wait(mysem); //update 
        snprintf(shared_msg->content, MAX_MSG_LENGTH, "%s", argv[1]); 
    
        /* critical section end */ 
    } 
    

    更新client.c

    int main(int argc, char *argv[]) 
    { 
    /* code to open posix shared memory and posix named semaphore */ 
    
    for(i=0; i<20; i++){ 
        /* critical section start */ 
    
        //operation of semaphore 
        while(loop < 15){ 
         printf("Type : %d, content : %s\n", shared_msg->type, shared_msg->content); 
         sleep(1); 
         loop++; 
        } 
        sem_post(mysem); 
    /* Critical section end */ 
    
        loop = 0; 
        printf("loop %d finished\n", i); 
        } 
    }