简体   繁体   English

getuid 为 root 返回不同的零

[英]getuid return different zero for root

I am with the following problem to run我有以下问题要运行

void main(void){
uid_t getuid(void);
gid_t getgid(void);

uid_t user_id;
gid_t group_id;

printf("user_id: %d\n",user_id);
printf("group_id: %d\n",group_id);
exit(0);
}

I am having the result : user_id: 134513819 and group_id: -1216946176 as the file belongs to the root and is running as root should not return:我得到的结果是: user_id: 134513819group_id: -1216946176因为该文件属于 root 并且以 root 身份运行不应返回:

user_id: 0
group_id: 0

also if anyone can clarify why it is returning a negative value appreciate .此外,如果有人能澄清为什么它返回负值,请欣赏。

Wrong types in printf. printf 中的类型错误。 %d is a signed decimal. %d 是有符号十进制。 You probably want %u.你可能想要 %u。

The number is negative because of the different binary representations of numbers.由于数字的二进制表示不同,因此该数字为负数。 For a signed decimal the first bit in the sequence of zeros and ones in your PC represents the sign: plus or minus.对于有符号十进制,PC 中 0 和 1 序列中的第一位表示符号:加号或减号。

For unsigned decimals the first bit represents an exponential of 2.对于无符号十进制,第一位表示 2 的指数。

So if you try to interpret a sequence of bits that represents an unsigned decimal (%u) as a signed decimal (%d), that first bit, which should translate to a numerical value like 2^7, gets interpreted as a plus or minus.因此,如果您尝试将表示无符号十进制 (%u) 的位序列解释为有符号十进制 (%d),那么第一个应该转换为 2^7 之类的数值的位将被解释为加号或减。

Unsigned 8 bit long decimals range from 0 to 255, signed 8 bit decimals range from -127 to 128, which also is a total of 256 different digits.无符号8位长小数范围从0到255,有符号8位小数范围从-127到128,也就是总共256位不同的数字。

See https://en.wikipedia.org/wiki/Signed_number_representations请参阅https://en.wikipedia.org/wiki/Signed_number_representations

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM