gpt4 book ai didi

可以在标准 C 中处理中断吗?

转载 作者:太空狗 更新时间:2023-10-29 15:17:51 26 4
gpt4 key购买 nike

在标准 C (ANSI/ISO) 中是否有服务硬件中断的方法?到目前为止,我看到的所有实现要么使用特定于编译器的语言扩展,要么使用预处理器指令。

我刚刚遇到标准 C 库的“信号”功能,但维基百科对其使用非常简单,我认为它不符合目的。

最佳答案

POSIX 信号允许用 C 编写的用户程序捕获和处理某些类型的中断和/或异常。这是我所知道的最标准的方法。

#include <stdio.h>
#include <signal.h>
#include <setjmp.h>
int a,b,*p;
jmp_buf jump_destination;

void exception_handler (int sg)
{
printf ("Error dereferencing pointer\n");
p=&b; /* pointer quick fix. */
longjmp(jump_destination,1); /* long GOTO... */
}

void main (void)
{
int i;

signal (SIGSEGV, exception_handler);
b=0; p=NULL;

setjmp(jump_destination); /* ...to this position */
printf ("Trying to dereference pointer p with value %08.8X... ",p);
printf ("After dereferencing pointer, its value is: %d\n", *p);
}

对于硬件中断,C没有明确的语义,主要是不需要。例如,Linux 设备驱动程序可以为硬件设备安装自己的中断处理程序。您只需使用负责处理中断的函数的地址调用 request_irq() 函数。

例如,这将为 RTC 芯片安装一个中断处理程序(假设它存在并在您的硬件中激活)

...
...
res=request_irq (8, /* que IRQ queremos */
interrupt_handler, /* address of handler */
IRQF_DISABLED, /* this is not a shared IRQ */
“mydriver", /* to be shown at /proc/interrupts */
NULL);
if (res!=0)
{
printk ("Can't request IRQ 8\n");
}
...
...

您的处理程序只是一个普通的 C 函数:

static irqreturn_t gestor_interrupcion (int irq, void *dev_id, struct pt_regs *regs)
{
/* do stuff with your device, like read time or whatever */
...
...
...

return IRQ_HANDLED; /* notify the kernel we have handled this interrupt */
}

这是可能的(使用常规 C 函数来处理硬件中断),因为处理程序本身是从另一个内核函数调用的,该函数负责保存当前上下文,因此被中断的进程不会注意到任何事情。如果您在“裸”计算机中处理中断,并且希望您的 C 代码不偏离标准,那么您将需要使用一些汇编程序来调用您的函数。

关于可以在标准 C 中处理中断吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21336730/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com