我正在尝试使用 asm volatile 为 read() 系统调用编写一个包装函数,但它不起作用,因为 res 不会改变它的值。
这是代码:
ssize_t my_read(int fd, void *buf, size_t count)
{
ssize_t res;
__asm__ volatile(
"int $0x80" /* make the request to the OS */
: "=a" (res), /* return result in eax ("a") */
"+b" (fd), /* pass arg1 in ebx ("b") */
"+c" (buf), /* pass arg2 in ecx ("c") */
"+d" (count) /* pass arg3 in edx ("d") */
: "a" (5) /* passing the system call for read to %eax , with call number 5 */
: "memory", "cc"); /* announce to the compiler that the memory and condition codes have been modified */
/* The operating system will return a negative value on error;
* wrappers return -1 on error and set the errno global variable */
if (-125 <= res && res < 0)
{
errno = -res;
res = -1;
}
return res;
}
这是int main ()
:
int main() {
int fd = 432423;
char buf[128];
size_t count = 128;
my_read(fd, buf, count);
return 0;
}
难道我做错了什么 ?也许是因为volatile
?
我试图调试代码,当 Eclipse 进入my_read(fd, buf, count);
并进入线路 __asm__ volatile(
时my_read
,它失败并进入if (-125 <= res && res < 0)
......
编辑 :
ssize_t my_read(int fd, void *buf, size_t count)
{
ssize_t res;
__asm__ volatile(
"int $0x80" /* make the request to the OS */
: "=a" (res) /* return result in eax ("a") */
: "a" (5) , /* passing the system call for read to %eax , with call number 5 */
"b" (fd), /* pass arg1 in ebx ("b") */
"c" (buf), /* pass arg2 in ecx ("c") */
"d" (count) /* pass arg3 in edx ("d") */
: "memory", "cc"); /* announce to the compiler that the memory and condition codes have been modified */
/* The operating system will return a negative value on error;
* wrappers return -1 on error and set the errno global variable */
if (-125 <= res && res < 0)
{
errno = -res;
res = -1;
}
return res;
}
和主要:
int main() {
int fd = 0;
char buf[128];
size_t count = 128;
my_read(fd, buf, count);
return 0;
}