Closed. This question needs details or clarity。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
                        
                        3个月前关闭。
                                                                                            
                
        
我想从连接到服务器的所有客户端收集数据,并且我最多要等待1秒钟。如何使用信号量?
我当前的代码:

int players=2;
while(1){
    //request for choice
    for(int i = 0; i<players; i++)
        sem_post(&sharedMemory->request_choice);
    //wait for data
    for (int i = 0;i<players; i++)
        //ok..I have data but not in 1 second..
        sem_wait(&sharedMemory->got_choice);


    //updating data..
}

最佳答案

POSIX platforms provide sem_timedwait()


  概要

#include <semaphore.h>
#include <time.h>

int sem_timedwait(sem_t *restrict sem,
       const struct timespec *restrict abstime);

  
  描述
  
  sem_timedwait()函数应锁定由引用的信号量
  semsem_wait()函数中一样。但是,如果信号量
  无法等待其他进程或线程才能锁定
  通过执行sem_post()功能解锁信号量,此等待
  当指定的超时时间到期时,应终止。
  
  当绝对时间指定为绝对时间时,超时将终止
  通过,以超时所依据的时钟为准(即,
  当该时钟的值等于或超过abstime时),或者
  abstime指定的绝对时间已经在
  通话时间。
  
  超时应基于CLOCK_REALTIME时钟。的
  超时的分辨率应为时钟的分辨率
  它基于的。 timespec数据类型定义为结构
  在<time.h>标头中。
  
  如果在任何情况下,函数都不会因超时而失败。
  信号量可以立即锁定。 abstime的有效性
  无需检查信号量是否可以立即锁定。
  
  返回值
  
  如果调用sem_timedwait()函数应返回零
  进程成功执行了对
  sem指定的信号量。如果呼叫失败,则状态为
  信号量的值应保持不变,并且该函数应返回一个
  值-1并设置errno表示错误。
  
  错误
  
  sem_timedwait()函数在以下情况下将失败:
  
  ...

[ETIMEDOUT]
    The semaphore could not be locked before the specified timeout expired.



该链接还提供了此示例用法:


/* Calculate relative interval as current time plus
   number of seconds given argv[2] */


if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
    perror("clock_gettime");
    exit(EXIT_FAILURE);
}
ts.tv_sec += atoi(argv[2]);


printf("main() about to call sem_timedwait()\n");
while ((s = sem_timedwait(&sem, &ts)) == -1 && errno == EINTR)
    continue;       /* Restart if interrupted by handler */

关于c - IPC:每秒从客户端收集数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59058246/

10-09 17:52
查看更多