0

I can't open serial port to start communication in linux ubuntu. I've tried this:

int OpenPort(void) {

int fd; 

fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);

if(fd == -1)
{
  printf("Failed to open port.\n");
}
else
{
    fcntl(fd, F_SETFL, 0);
    printf("Opened!\n");
}

return(fd);
}

int main()
{
  int x = OpenPort();
  printf("%i\n", x);

  exit(0);
}

I'm new in linux and found this code online, but it doesn't work for me.

3
  • What is the error? Try to replace printf("Failed to open port.\n") to printf("Failed to open port: %s.\n", strerror(errno)) or perror("Failed to open port."). Commented Feb 25, 2014 at 12:51
  • 1
    When a system call fails, you should print the value of errno which contains the error code. You can get a nice printable string with the strerror function. You can also use the perror function to print the message directly. Commented Feb 25, 2014 at 12:51
  • error is Permission denied Commented Feb 25, 2014 at 12:52

1 Answer 1

2

You need to run as superuser/root to access serial port in linux. Try running your binary as sudo. If you can verify this is the problem but you do not want your process to be run by root user there are options you can use in your code to obtain root privileges. This answer might be useful reading How to programmatically gain root privileges?

Sign up to request clarification or add additional context in comments.

3 Comments

It works with sudo, but how to run it without it? How to get permissions? I'm running ubuntu as administrator.
@user2081328 See that answer that I have linked to in my edit.
@user2081328 By the way I noticed you have asked 13 questions here on SO but have not accepted any answers. If you find that an answer solved your problem you can accept it. This helps people who look at your question in future to see which is the best solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.