int WriteCommuData(const char *port, const char *data)
{
int res;
char fifoName[64];
static int fifo_fd = -1;
static char oldPort[32] = {'\0'};
int len, wrote;
if (port == NULL || strlen(port) <= 0 || data == NULL || (len = strlen(data)) <= 0)
return -1;
if (strcmp(port, oldPort) != 0)
{
if (fifo_fd != -1)
close(fifo_fd);
strncpy(oldPort, port, sizeof(oldPort));
}
if (fifo_fd == -1)
{
snprintf(fifoName, sizeof(fifoName), "/tmp/%s", port);
if (access(fifoName, F_OK) == -1)
{
res = mkfifo(fifoName, 0777);
if (res != 0)
{
printf("mkfifo error");
return -1;
}
}
fifo_fd = open(fifoName, O_WRONLY|O_NONBLOCK);
// 非阻塞模式打开写管道时,如果当前没有读管道打开,则会返回No such device or address
printf("name=%s, fd=%d", fifoName, fifo_fd);
if (fifo_fd == -1)
{
printf("open fifo %s", strerror(errno));
return -1;
}
}
wrote = 0;
while (wrote < len)
{
res = write(fifo_fd, data + wrote, len - wrote);
printf("res=%d, errno=%d", res, errno);
if (res == -1)
{
if (errno == EAGAIN)
continue;
else
{
close(fifo_fd);
fifo_fd = -1;
return -1;
}
}
wrote += res;
}
return wrote;
}
int ReadCommuData(const char *port, char *buf, int bufLen)
{
int res;
char fifoName[64], readBuf[PIPE_BUF];
static int fifo_fd = -1;
static char oldPort[32] = {'\0'};
int rd;
if (port == NULL || strlen(port) <= 0 || buf == NULL)
return -1;
if (strcmp(port, oldPort) != 0)
{
if (fifo_fd != -1)
close(fifo_fd);
strncpy(oldPort, port, sizeof(oldPort));
}
if (fifo_fd == -1)
{
snprintf(fifoName, sizeof(fifoName), "/tmp/%s", port);
if (access(fifoName, F_OK) == -1)
{
res = mkfifo(fifoName, 0777);
if (res != 0)
{
printf("mkfifo error");
return -1;
}
}
fifo_fd = open(fifoName, O_RDONLY|O_NONBLOCK);
printf("name=%s, fd=%d", fifoName, fifo_fd);
if (fifo_fd == -1)
{
printf("open fifo error");
return -1;
}
}
rd = 0;
while (rd < bufLen)
{
res = read(fifo_fd, readBuf, bufLen);
if (res == -1)
{
if (errno == EAGAIN)
break;
else
{
close(fifo_fd);
fifo_fd = -1;
return -1;
}
}
memcpy(buf + rd, readBuf, res);
rd += res;
}
buf[rd] = '\0';
return rd;
}