Linux读写命名管道

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值