嵌入式linux输出重定向实现(串口telnet互切)

对于设备批量挂机测试、远程客诉处理等场景,加个串口重定向到telnet端口打印功能还是很实用的,为此封装成了独立文件,话不多说,复制进工程里直接能用。

C文件代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <netinet/tcp.h>
#include <pthread.h>
#include <errno.h>
#include "ls_output_redirect.h"

#define OUTPUT_PORT 401

static int g_redirect_running = 0;
static int g_listen_fd = -1;
static int g_client_fd = -1;
static pthread_t g_listen_pid = 0;
static pthread_t g_recv_pid = 0;
static int g_serial_fd = -1;
static int g_serial_err_fd = -1;
static int g_telnet_fd = -1;
static int g_telnet_err_fd = -1;
static int g_client_data_fd = -1;

/// @brief 输出重定向到串口
/// @param
/// @return
int __LS_OUTPUT_REDIRECT_Redirect2Serial(void)
{
    if (g_client_data_fd < 0)
    {
        return -1;
    }
    if (dup2(g_serial_fd, STDOUT_FILENO) < 0)
    {
        printf("%s %d: g_serial_fd dup2 STDOUT_FILENO failed\n", __func__, __LINE__);
    }

    if (dup2(g_serial_err_fd, STDERR_FILENO) < 0)
    {
        printf("%s %d: g_serial_fd dup2 STDOUT_FILENO failed\n", __func__, __LINE__);
    }

    close(g_client_data_fd);
    close(g_serial_fd);
    close(g_serial_err_fd);
    g_client_data_fd = -1;
    g_serial_fd = -1;
    return 0;
}

/// @brief 
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值