C 语言中用于等待的函数102
在 C 语言编程中,可能需要暂停程序执行或等待某个事件发生。为此,C 语言提供了几个有用的函数,用于不同情况下的等待。
1. sleep() 函数
sleep() 函数使程序睡眠指定的时间段,单位为秒。语法如下:```c
#include
unsigned int sleep(unsigned int seconds);
```
函数返回睡眠时间的剩余秒数,如果被中断则返回 0。例如:```c
#include
#include
int main() {
printf("程序开始执行。");
sleep(5);
printf("程序睡眠 5 秒后继续执行。");
return 0;
}
```
2. usleep() 函数
usleep() 函数使程序睡眠指定的时间段,单位为微秒。语法如下:```c
#include
int usleep(useconds_t microseconds);
```
函数返回 0 表示睡眠成功,否则返回 -1。例如:```c
#include
#include
int main() {
printf("程序开始执行。");
usleep(500000); // 500 毫秒
printf("程序睡眠 500 毫秒后继续执行。");
return 0;
}
```
3. nanosleep() 函数
nanosleep() 函数使程序睡眠指定的时间段,单位为纳秒。语法如下:```c
#include
int nanosleep(const struct timespec *req, struct timespec *rem);
```
参数 req 指定睡眠时间,参数 rem 用于存储睡眠的剩余时间。函数返回 0 表示睡眠成功,否则返回 -1。例如:```c
#include
#include
int main() {
printf("程序开始执行。");
struct timespec req;
req.tv_sec = 0;
req.tv_nsec = 500000000; // 500 毫秒
nanosleep(&req, NULL);
printf("程序睡眠 500 毫秒后继续执行。");
return 0;
}
```
4. wait() 和 waitpid() 函数
wait() 和 waitpid() 函数用于等待子进程退出。语法如下:```c
#include
pid_t wait(int *status);
pid_t waitpid(pid_t pid, int *status, int options);
```
wait() 等待任何子进程退出,而 waitpid() 等待指定 PID 的子进程退出。函数返回子进程的 PID,如果出错则返回 -1。例如:```c
#include
#include
int main() {
int status;
pid_t child_pid = fork();
if (child_pid == 0) {
// 子进程代码
printf("子进程正在运行。");
exit(0);
} else {
// 父进程代码
wait(&status);
printf("子进程已退出,状态为 %d", status);
}
return 0;
}
```
5. poll() 和 epoll() 函数
poll() 和 epoll() 函数用于监控多个文件描述符,等待事件发生。语法如下:```c
#include
int poll(struct pollfd *fds, nfds_t nfds, int timeout);
#include
int epoll_create1(int flags);
int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);
int epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout);
```
poll() 和 epoll() 是低级 I/O 多路复用函数,用于高效地处理多个文件描述符。poll() 一次性检查所有文件描述符,而 epoll() 使用事件通知机制,减少了轮询开销。
选择合适的等待函数取决于特定的需求和应用程序要求。对于简单的延迟或等待,sleep() 和 usleep() 是合适的。对于更精确的计时,可以使用 nanosleep()。进程管理可以通过 wait() 和 waitpid() 函数,而文件描述符监控可以通过 poll() 和 epoll() 函数实现。
2024-11-22
下一篇:C语言中输出有引号的字符串
ThinkPHP 数据库删除深度指南:从基础到高级,安全高效管理数据
https://www.shuihudhg.cn/134414.html
PHP ZipArchive 深度解析:创建、读取、解压与高效管理ZIP文件类型
https://www.shuihudhg.cn/134413.html
Python的极致简洁与强大:用10行代码解锁无限可能
https://www.shuihudhg.cn/134412.html
PHP 逐行读取文件内容详解:从基础到高性能实践
https://www.shuihudhg.cn/134411.html
精通Java编程:从每日代码习惯到高效开发实践
https://www.shuihudhg.cn/134410.html
热门文章
C 语言中实现正序输出
https://www.shuihudhg.cn/2788.html
c语言选择排序算法详解
https://www.shuihudhg.cn/45804.html
C 语言函数:定义与声明
https://www.shuihudhg.cn/5703.html
C语言中的开方函数:sqrt()
https://www.shuihudhg.cn/347.html
C 语言中字符串输出的全面指南
https://www.shuihudhg.cn/4366.html