首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

Linux write系统调用有关问题

2012-08-22 
Linux write系统调用问题最近在学习Linux C 编程,碰到一个疑问程序1:C/C++ code#include unistd.h#inclu

Linux write系统调用问题
最近在学习Linux C 编程,碰到一个疑问
程序1:

C/C++ code
#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);}

编译后在终端中运行,运行结果是输出(即将内容写入到标准输出流中)了"Here is some date"。如果稍微改变一下write的实参值,将第一个write函数的第三个参数改为17,运行结果如下:
  Here is some data
  A error has occured on file descriptior 1
将18改为20,在终端中运行的结果为:
  Here is some data
  A error has occured on file descriptior 1

程序2:
C/C++ code
#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);}

编译运行后的结果为:
Here is some
A
The value returned by function write is 18

程序2运行后,第二行为什么会输出一个A ? 这个A明显是if语句块里的那个write函数的结果。如果nb的值确实是18,那么按理来说,if语句就不会执行,就不会有这个A;如果nb的值不是18,那么按理第二行应该输出:A error has occured on file descriptior 1\n。 求高手解释

[解决办法]
首先,write第三个参数是输出长度,程序1里你写18,那必然会输出18个字符,写17必然输出17个字符,返回值肯定不是18呀,第三个参数是20的话,貌似会多输出一个\0。。

程序2:write第一个参数是输出位置吧,2好像是stderr?还是stdin??忘了。
你的if忘了括括号了
C/C++ code
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和后面行的输出是没有关系的,应该有关系,不行,你自己试一下。

热点排行