许多其他答案提到使用某种协议来处理数据,我认为这是正确的方法。该协议可以尽可能简单或复杂。我提供了一些你可能会觉得有用的例子
1。
在一个简单的情况下,你只需要一个长度字节,后面跟着数据字节(即C字符串)。
+--------------+
| 长度字节 |
+--------------+
| 数据字节 |
+--------------+
作者:
uint8_t foo[UCHAR_MAX+1];
uint8_t len;
int fd;
mkfifo("/tmp/myfifo", 0660);
fd = open("/tmp/myfifo", O_WRONLY);
memset(foo, UCHAR_MAX+1, 0);
len = (uint8_t)snprintf((char *)foo, UCHAR_MAX, "Hello World!");
write(fd, len, 1);
write(fd, foo, strlen(foo));
读者:
uint8_t buf[UCHAR_MAX+1];
uint8_t len;
int fd;
fd = open("/tmp/myfifo", O_RDONLY);
memset(buf, UCHAR_MAX+1, 0);
read(fd, len, 1);
read(fd, buf, len);
在更复杂的情况下,您可能会有一个长度字节,后跟包含不止一个简单C字符串的数据字节。
+----------------+
| 长度字节 |
+----------------+
| 数据类型字节 |
+----------------+
| 数据字节 |
+----------------+
常见头部:
#define FOO_TYPE 100
#define BAR_TYPE 200
typedef struct {
uint8_t type;
uint32_t flags;
int8_t msg[20];
} __attribute__((aligned, packed)) foo_t;
typedef struct {
uint8_t type;
uint16_t flags;
int32_t value;
} __attribute__((aligned, packed)) bar_t;
作者:
foo_t foo;
unsigned char len;
int fd;
mkfifo("/tmp/myfifo", 0660);
fd = open("/tmp/myfifo", O_WRONLY);
memset(&foo, sizeof(foo), 0);
foo.type = FOO_TYPE;
foo.flags = 0xDEADBEEF;
snprintf(foo.msg, 20-1, "Hello World!");
/* The length byte is written first followed by the data. */
len = sizeof(foo);
write(fd, len, 1);
write(fd, foo, sizeof(foo));
读者:
uint8_t buf[UCHAR_MAX+1];
uint8_t len;
uint16_t type;
union data {
foo_t * foo;
bar_t * bar;
}
int fd;
fd = open("/tmp/myfifo", O_RDONLY);
memset(buf, UCHAR_MAX+1, 0);
read(fd, len, 1);
read(fd, buf, len);
memcpy(&type, buf, sizeof(type));
switch(type) {
case FOO_TYPE:
data.foo = (foo_t)buf;
printf("0x%08X: %s\n", data.foo.flags, data.foo.msg);
break;
case BAR_TYPE:
data.bar = (bar_t)buf;
printf("0x%04X: %d\n", data.bar.flags, data.bar.value);
break;
default:
printf("unrecognized type\n");
}
1 - 这段代码是凭记忆编写的,未经过测试。
sizeof(char)
始终等于1。 - Dietrich Epp