日期:2014-05-16  浏览次数:20761 次

关于sem_trywait的一个问题
代码如下:

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

#include <fcntl.h>
#include <sys/stat.h>
#include <semaphore.h>

int main(int argc, char *argv[])
{
  sem_t *sem = NULL;
  
  sem = sem_open(argv[1], O_RDWR);
  if (sem == SEM_FAILED)
  {
    fprintf(stderr, "%s\n", "Can not open a semaphore");
    exit(EXIT_FAILURE);
  }
  
  int sem_value = 0;
  int ret = sem_getvalue(sem, &sem_value);
  printf("%d\n", sem_value);
  if (ret == -1) 
  {
    perror("Can not get the value of a semaphore");
  }

  /* Why don't retuen a error number of EAGAIN(11) */
  ret = sem_trywait(sem);
  printf("%d\n", ret);
  if (ret == EAGAIN)
  {
    fprintf(stdout, "%s\n", "can not get resource");
  }

  return 0;
}

书上说的是当所指定的信号量已经是0时,sem_trywait将返回错误EAGAIN,我试了好多次,返回的ret值却不是,求指点啊,谢谢。。。

------解决方案--------------------
楼主搞错了吧,失败时返回值是-1,要检查errno

RETURN VALUE

    The sem_trywait() and sem_wait() functions shall return zero if the calling process successfully performed the semaphore lock operation on the semaphore designated by sem. If the call was unsuccessful, the state of the semaphore shall be unchanged, and the function shall return a value of -1 and set errno to indicate the error.