Linux write系统调用问题
最近在学习Linux C 编程,碰到一个疑问
程序1:
#include <unistd.h>#include <stdlib.h>int main() { if ((write(1, "Here is some date\n", 18)) != 18) write(2, "A error has occured on file descriptior 1\n", 42); exit(0);}
#include <unistd.h>#include <stdlib.h>#include <stdio.h>int main() { int nb; nb = (int)write(1, "Here is some\n", 18); if (nb != 18) write(2, "A error has occured on file descriptior 1\n", 42); printf("\nThe value returned by the function write is %d\n", nb); exit(0);}
if (nb != 18){ write(2, "A error has occured on file descriptior 1\n", 42); printf("\nThe value returned by the function write is %d\n", nb);}
[解决办法]
nb = (int)write(1, "Here is some\n", 18);
因为你的数据不够18个字节,但write仍输出内存中some\n以后的内容,这个内容是随机不可预知的。它可能是A?,也可能是其它任何内容。这个A和后面行的输出是没有任何关系的。
[解决办法]
常量字符串按顺序存储在常量区域的.
"Here is some\n"
"A error has occured on file descriptior 1\n"
这两个常量字符串的地址是紧挨着的, 当第一个字符串的访问越界后就访问到第二个字符串了.
你可以打印他们的地址来验证.
[解决办法]
1.程序1:write函数的第三个参数改为17输出结果应该为:
Here is some dataA error has occured on file descriptior 1。这个没有问题,看你的结果分为两行,可能是你拷贝的问题。所以程序1没有问题。
2.程序2的话,这个我试了一下,确实是,我是在Ubuntu下试的,我的建议是nb = (int)write(1, "Here is some\n", 18);中的18改成14,15,16都可以。但是从17数字往大变的话。就会出现问题,依此输出A error has occured on file descriptior 1这个字符串里面的的值。我以为和stdout和stderr这些东西有关,所以说,如果想得到正确的值,nb = (int)write(1, "Here is some\n", 18);中的值不能比字符串实际常打太多,我不同意楼上的A和后面行的输出是没有关系的,应该有关系,不行,你自己试一下。