c - 我正在尝试编写一个从串行端口获取信息的程序(它不是文件)。

标签 c serial-port

我从 C 语言开始。 我正在尝试编写一个从串行端口获取信息的程序(它不是文件)。串口不断地发送信息。我写了一个小程序,但我一直遇到段错误:11。主要目标是将我们通过串行端口获取的信息存储在文件中。 感谢您的帮助。

#include <stdio.h>   
#include <string.h>  
#include <unistd.h>  
#include <fcntl.h>   
#include <errno.h>   
#include <termios.h> 
#include <stdlib.h>
#include <unistd.h>
#include <termios.h>
#include <sys/ioctl.h>

int open_port();

main()
{

    printf("\n\nStarting...\n\n");
    open_port();

    return (1);
}

int open_port()
{
    int fd;
    int bytes;
    int string;

    char *input;


    struct termios options;

    /* open usb entry */
    fd = open("/dev/cu.usbserial-FTF6001E", O_RDWR | O_NOCTTY | O_NDELAY);


    /* check it could be opened */
    if (fd == -1)
    {
        perror("\n\nopen_port: Unable to open /dev/cu.usbserial-FTF6001E - ");
    }    
    else{

        ioctl(fd, FIONREAD, &bytes);
        printf("\n\nbytes: %d\n\n", bytes);



        fcntl(fd, F_SETFL, 0);

        /* get port options currently set*/
        tcgetattr(fd, &options);

        options.c_cflag &= ~PARENB;
        options.c_cflag &= ~CSTOPB;
        options.c_cflag &= ~CSIZE;
        options.c_cflag |= CS8;

        /* Set the baud rates to 19200...*/
        cfsetispeed(&options, B9600);
        cfsetospeed(&options, B9600);

        /* Enable the receiver and set local mode...*/
        options.c_cflag |= (CLOCAL | CREAD);

        /*Set the new options for the port...*/
        tcsetattr(fd, TCSANOW, &options);

        *input = (char) malloc (string * sizeof(char));

        if (input == 0){

            fputs("\n\nUps! Failed to allocate memory!!!\n\n",stdout);

        }

        if ( fgets (input , 100 , fd) != NULL ){
            puts (input);
            fclose (fd);
        }

        printf("input = %s", input);

    }

最佳答案

你的问题出在这里:

*input = (char) malloc (string * sizeof(char));

首先,您希望分配给 input,而不是 *input。因为 input 还不是指向任何地方的有效指针,所以 *input 是未定义的行为。

但是,即使解决了这个问题,您仍然会遇到问题(a)。您的 string 变量尚未初始化,因此在程序启动时将被设置为堆栈上的任何垃圾。这意味着您不太可能从 malloc 返回正确数量的内存。

此外,您还将 malloc 的返回值转换为 char!您永远不应该在 C 中转换 malloc 的返回值(例如转换为 char *),因为它隐藏了某些错误,这些错误可能会在以后导致其他问题。

当然不应该将其转换为char,因为这几乎肯定会丢失信息。显式转换是告诉编译器您知道自己在做什么 - 我认为这在这里不太准确:-)

事实上,我根本不知道为什么要动态分配内存,因为您只读取过 100 个字节。放弃malloc并定义input:

char input[100];
input[0] = '\0';
<小时/>

(a)甚至可能还有更多问题,它们只是我立即想到的问题。不过,我建议首先修复这些问题,因为它们肯定是导致段错误的原因。

然后,如果仍有问题,请回来提出另一个问题。

关于c - 我正在尝试编写一个从串行端口获取信息的程序(它不是文件)。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11948648/

相关文章:

c - 查找动态分配的 unsigned long long 数组的长度

c - printf/sprintf 编译器警告是概念上的中断吗?

linux - 在 Linux 中与 CashCode 账单接受器通信

串口的 node.js 路径

Bash 从 ttyUSB0 读取并发送到 URL

c - 读/写 txt 字符串

arrays - 在 C 错误 "expected expression before ‘]’ token 中初始化数组”

c - 在 C 中获取目录列表

c# - 使用 C# 监控多个 com 端口

matlab - 在 Matlab 中打开串行对象很慢