我从 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);
}