C++ 中的中断

发布于 2024-09-25 13:32:18 字数 40 浏览 1 评论 0原文

我正在尝试理解中断,并正在寻找使用中断的简单代码。有人可以帮我吗?

I am trying to understand interrupts and am looking for a simple code that uses interrupts. Could somebody please help me with it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绝不放开 2024-10-02 13:32:18

以下是使用警报功能的两个示例。警报会导致 SIGALRM 在您调用该函数后 n 秒发生。

该程序将运行 3 秒,然后因 SIGALRM 信号而终止。

#include <signal.h>
#include <unistd.h>

int main() {
    alarm(3);
    while(true);
}

在这种情况下,我们希望捕获 SIGALRM,并优雅地结束一条消息:

#include <signal.h>
#include <unistd.h>
#include <iostream>

volatile bool alarmed = false;

void alrm_handler(int) {
    alarmed = true;
}

int main() {
    signal(SIGALRM, alrm_handler);

    alarm(3);
    while(not alarmed);

    std::cout << "done" << std::endl;
}

Here are two examples using the alarm function. alarm causes SIGALRM to happen n seconds after you call that function.

This program will run for 3 seconds, and then die with SIGALRM.

#include <signal.h>
#include <unistd.h>

int main() {
    alarm(3);
    while(true);
}

In this case, we'd like to catch SIGALRM, and die gracefully with a message:

#include <signal.h>
#include <unistd.h>
#include <iostream>

volatile bool alarmed = false;

void alrm_handler(int) {
    alarmed = true;
}

int main() {
    signal(SIGALRM, alrm_handler);

    alarm(3);
    while(not alarmed);

    std::cout << "done" << std::endl;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文