先看下面这段代码:
- char shell_return[64];
- printf("serving client on fd %d send %s\n",fd,ch);
- popen_fd=popen("/bin/cat /etc/issue | /bin/grep release","r");
- if (popen_fd!=NULL)
- {
- fread(shell_return,sizeof(char),sizeof(shell_return)-1,popen_fd);
- shell_return[sizeof(shell_return)-1]='\0';
- printf("\n###\n%s\n###\n",shell_return);
- }
上面这段代码使用匿名管道接收shell的标准输出。
在终端执行shell是这样的:
[root@allyestestR420 get_de_data]# /bin/cat /etc/issue | /bin/grep release
CentOS release 5.8 (Final)
[root@allyestestR420 get_de_data]#
但是我的程序结果是:
###
CentOS release 5.8 (Final)
}1
###
出现这种情况的原因是shell_return没有初始化,将声明变量时的代码改成char shell_return[64] = {0};就可以了。
我们再来深入分析下出现这种错误的原因:
你前面没有初始化这段内存,里面的值都是随机的,你拷贝的那个长度的字符后面不是0,所以输出了你预期之外的那些字符。
转载于:https://blog.51cto.com/305460883/1124228