許多其他答案都提到使用某種協議來處理數據,我相信這是正確的方法。該協議可以根據需要簡單或複雜。我提供了幾個例子,您可能會發現有用。
在一種簡單的情況下,你可能只有一個長度字節之後是數據字節(一個或多個)(即C字符串)。
+--------------+
| length byte |
+--------------+
| data byte(s) |
+--------------+
編劇:
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!");
/* The length byte is written first followed by the data. */
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);
/* The length byte is read first followed by a read
* for the specified number of data bytes.
*/
read(fd, len, 1);
read(fd, buf, len);
在更復雜的情況下,可能必須的長度字節後跟包含多個數據字節比簡單的C字符串。
+----------------+
| length byte |
+----------------+
| data type byte |
+----------------+
| data byte(s) |
+----------------+
公共頭:
#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);
/* The length byte is read first followed by a read
* for the specified number of data bytes.
*/
read(fd, len, 1);
read(fd, buf, len);
/* Retrieve the message type from the beginning of the buffer. */
memcpy(&type, buf, sizeof(type));
/* Process the data depending on the 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 - 此代碼是從內存寫入,未經測試。
注意:ANSI C保證'sizeof(char)'總是等於1. – 2010-05-20 01:54:57