The first thing you should do is check the value of errno
. The open
call, if it returns -1, will set errno
to a value indicating what the actual problem is.
And, based on your comment that it's Permission denied
and your program works when run under sudo
, it's probably a permissions problem with the /dev/ttyS0
device file.
I get a similar issue under Debian 6:
pax> ls -al /dev/ttyS0
crw-rw---- 1 root dialout 4, 64 Mar 23 21:00 /dev/ttyS0
pax> echo xyzzy >/dev/ttyS0
bash: /dev/ttyS0: Permission denied
You may find you need to add your user to the dialout
group (or another group, depending on how far Ubuntu deviates from my beloved Debian) to be allowed access:
pax> id -Gn
pax cdrom floppy audio dip video plugdev netdev bluetooth scanner
pax> sudo adduser pax dialout
[sudo] password for pax:
Adding user pax to group dialout
Done.
<< Restart done here to ensure new group picked up >>
pax> id -Gn
pax dialout cdrom floppy audio dip video plugdev netdev bluetooth scanner
errno
? That should be the first thing you look at.