我在 C 程序中的/tmp/mypipe 中创建了一个管道。管道用于在程序中的两个模块上发送和接收命令字节。模块按照以下结构发送数据:
struct controller
{
int command;
char data[100];
}
我想以相同的格式将数据发送到/tmp/mypipe。我尝试了下面的命令,C 程序接收到数据。
echo -e "\x00\x00\x00\x04"www.google.com > /tmp/mypipe
但是,程序接收到的数据格式如下:
control.command = 67108864
control.data = www.google.com
我想要的是仅将 control.command 作为数字 4 接收。我尝试了通过 google 找到的多个建议。但是,当我尝试将数据重定向到管道时,它失败了。
如有任何帮助,我们将不胜感激。
最佳答案
您很可能使用的是小端机器,因此您应该以小端方式显示数字
echo -e "\x04\x00\x00\x00"www.google.com > /tmp/mypipe
或者,最好在接口(interface)的约定中选择字节序,并确保在代码中将其转换为机器的字节序
NAME
htonl, htons, ntohl, ntohs - convert values between host and network byte order
SYNOPSIS
#include <netinet/in.h>
uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);
DESCRIPTION
The htonl() function converts the unsigned integer hostlong from host byte order to network byte order.
The htons() function converts the unsigned short integer hostshort from host byte order to network byte order.
The ntohl() function converts the unsigned integer netlong from network byte order to host byte order.
The ntohs() function converts the unsigned short integer netshort from network byte order to host byte order.
On the i80x86 the host byte order is Least Significant Byte first, whereas the network byte order, as used on the Internet, is Most Significant Byte first.
关于c - 将 ASCII 字节流发送到管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15944725/