2012-04-26 62 views
2

我在一个小程序中包含了一些示例ASM代码来执行测试。C程序中的ASM代码导致分段错误

我的计划是:

#include <stdio.h> 

static inline 
unsigned char inb (int port) { 
    unsigned char data; 
    asm volatile("inb %w1,%0" : "=a" (data) : "d" (port)); 
    return data; 
} 

int main() 
{ 
    printf("hello world %d\n", inb(22)); 
    return 0; 
} 

当我运行程序时,它在执行ASM代码时崩溃段故障。 有人能告诉我这个小程序有什么问题吗?非常感谢。

+0

这是什么编译器? – Ben 2012-04-26 09:36:31

+0

我在linux上使用gcc – mike 2012-04-26 09:46:17

回答

2

如果您的操作系统是Windows或Linux,最有可能您的程序被终止,因为操作系统不允许常规应用程序访问I/O端口。

+0

是的,访问priviledge是问题 – mike 2012-04-26 10:34:24

7

在允许使用端口I/O之前,您需要使用ioperm。另外,请注意内核已经提供inb and outb functions

使用ioperm(2)或者iopl(2)告诉内核允许 用户空间应用程序访问有问题的I/O端口。如果失败 ,则会导致应用程序收到分段错误。

+0

它的工作原理,非常感谢 – mike 2012-04-26 10:16:31

+1

@mike一定要[接受答案](http://meta.stackexchange.com/questions/5234/how如果这对你有帮助的话,你可以接受一个答案)。 – philipvr 2012-04-26 16:17:46

0

你的语法是绝对正确的。只需在您的系统上找到并使用有效或未使用的端口即可。