trywait.c
来自「这个是学习嵌入式开发的重要例子」· C语言 代码 · 共 55 行
C
55 行
#include <stdio.h>#include <stdlib.h>#include <semaphore.h>#include <string.h>#include <errno.h>#include <sys/stat.h>#include <fcntl.h>int main(int argc, char **argv){ if (argc < 2) { fprintf(stdout, "Usage: %s <name>\n", argv[0]); exit(1); } sem_t *sem = NULL; if ((sem = sem_open(argv[1], O_RDONLY)) == SEM_FAILED) { fprintf(stderr, "sem_open() failed: %s\n", strerror(errno)); exit(1); } int value; //int sem_getvalue(sem_t *restrict sem, int *restrict sval); sem_getvalue(sem, &value); fprintf(stdout, "value = %d\n", value); //int sem_trywait(sem_t * sem); //int sem_wait(sem_t * sem); if (sem_trywait(sem) < 0) { fprintf(stderr, "sem_wait() failed: %s\n", strerror(errno)); if (errno == EAGAIN) { fprintf(stdout, "sem_trywait() returned EAGAIN.\n"); } else { sem_close(sem); exit(1); } } sem_getvalue(sem, &value); fprintf(stdout, "value = %d\n", value); sem_close(sem); return 0;}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?