为什么Linux系统调用返回类型“long”?

我正在阅读
Linux内核开发,第3版,了解内核实现和设计.第5章是关于系统调用.作者显示了使用SYSCALL_DEFINE0宏定义的系统调用声明的示例,该宏在该特定示例中展开为:

asmlinkage long sys_getpid(void)

他进一步说:

[…] For compatibility between 32- and 64-bit systems,system calls defined to return an int in user-space return a long in the kernel.

他不会比这更深刻,我不能完全理解为什么会这样.为什么要使用与32位和64位系统相关的长期关系?为什么我们不能返回一个简单的int?

解决方法

因为在许多
64 bits机器(例如x86-64)上用于常见的GCC编译器sizeof(int)== 4但是sizeof(void *)== 8&&的sizeof(长)== 8;这被称为I32LP64(或只是LP64)
data model

例如,在Linux / x86-64系统上编译并运行以下程序:

#include<stdio.h>
#include<stdint.h>
int main ()
{
  printf ("sizeof(int)=%d\n",(int) sizeof (int));
  printf ("sizeof(intptr_t)=%d\n",(int) sizeof (intptr_t));
  printf ("sizeof(short)=%d\n",(int) sizeof (short));
  printf ("sizeof(long)=%d\n",(int) sizeof (long));
  printf ("sizeof(long long)=%d\n",(int) sizeof (long long));
  printf ("sizeof(void*)=%d\n",(int) sizeof (void *));
  return 0;
}

在我的系统上使用gcc -Wall s.c -o编译并在我的Debian / Sid / x86-64(i3770k处理器,GCC 4.8.2)上运行./s:

sizeof(int)=4
sizeof(intptr_t)=8
sizeof(short)=2
sizeof(long)=8
sizeof(long long)=8
sizeof(void*)=8

在32位模式下使用gcc -m32 -Wall s.c -o s32编译并运行./s32:

sizeof(int)=4
sizeof(intptr_t)=4
sizeof(short)=2
sizeof(long)=4
sizeof(long long)=8
sizeof(void*)=4

如果使用gcc -mx32 -O3 -Wall s.c -o sx32编译x32,我得到相同的输出!

BTW,也许更好的问题是为什么不使用intptr_t ….我不知道(可能是一个习惯问题; when Linus首先开始编写他的内核,C99标准定义< stdint.h>和intptr_t-不存在).

阅读更多关于ABIs,特别是仔细阅读X86-64 ABI(另见x32 ABI …)和x86 calling conventions的wikipage.

dawei

【声明】:唐山站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。