c open() Undefined error: 0 on os x - c

On a mac running 10.8 i am trying to open a serial port.
ls /dev/cu* returns:
/dev/cu.Bluetooth-Modem /dev/cu.Bluetooth-PDA-Sync /dev/cu.usbserial-A1009TT7
i can see the port is there but when i try to open it i get Undefined error: 0(0). This is my code i use to open the port.
char *path = "/dev/cu.usbserial-A1009TT7";
open(path , O_RDWR | O_NOCTTY | O_NONBLOCK); // open the port
if (file == -1) {
printf("Error opening port : %s(%d).\n", strerror(errno), errno);
close(file);
return -1;
}
anyone have any idea why the port wont open?
thanks in advance.

Whoops! You meant to type this:
file = open(path , O_RDWR | O_NOCTTY | O_NONBLOCK);
^^^^^^^
Also, there is no need to close a file descriptor that isn't open.
if (file == -1) {
printf(...);
// close(file); Completely unnecessary. It's not valid!
return -1;
}

Related

What is the meaning of No such device or address(Error code 6)

I am trying to open a serial port with using c code and I have created a node with the following command;
mknod /tmp/ttyACM0 c 100 0;
chmod 700 /tmp/ttyACM0;
and then run an executable file that opens a serial port with the following method;
static int OpenSerialPort(const char *bsdPath)
{
int fileDescriptor = -1;
struct termios options;
fileDescriptor = open(bsdPath, O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fileDescriptor == -1 || flock(fileDescriptor, LOCK_EX) == -1 )
{
printf("Error opening serial port %s - %s(%d).\n",
bsdPath, strerror(errno), errno);
goto error;
}
if (fcntl(fileDescriptor, F_SETFL, 0) == -1)
{
printf("Error clearing O_NONBLOCK %s - %s(%d).\n",
bsdPath, strerror(errno), errno);
goto error;
}
if (ioctl(fileDescriptor, TIOCEXCL, (char *) 0) < 0) {
printf("Error setting TIOCEXCL %s - %s(%d).\n",
bsdPath, strerror(errno), errno);
goto error;
}
memset(&options,0,sizeof(options));
options.c_iflag=0;
options.c_oflag=0;
options.c_cflag=CS8|CREAD|CLOCAL;
options.c_lflag=0;
options.c_cc[VMIN]=1;
options.c_cc[VTIME]=5;
cfsetospeed(&options, B115200);
cfsetispeed(&options, B115200);
if (tcsetattr(fileDescriptor, TCSANOW, &options) == -1)
{
printf("Error setting tty attributes %s - %s(%d).\n",
bsdPath, strerror(errno), errno);
goto error;
}
return fileDescriptor;
error:
if (fileDescriptor != -1)
{
close(fileDescriptor);
}
exit(1);
return -1;
}
and it returns;
Error opening serial port /tmp/ttyACM0 - No such device or address(6).
There is actually a ttyACM0 file under /tmp directory but it returns me the error message. What can I do to pass this error?
EDIT:
When I look at the /proc/devices file, there is not a ttyACM0 device. Now I think my problem's reason can be this.
A device node does not mean that the device actually exists. When you open it the kernel tries to find the matching device and if it doesn't exists you get the above error.
Any Linux system form the last decade will create device nodes for existing devices automatically through udevd. That you had to create it manually is a strong indication the device doesn't exist at all just as the error says.

create new file with system calls

Im trying to create a new file / overwrite an existing file using systemcalls , but for some reason I have two problems:
1. When I'm first running the program it exits with value 0, so it seems like it created the file successfully, but I can't see anything in my project directory.
then when I secondly running the program the file is created, but an error message is printed on the screen.
2. Also after the first iteration of the program, I can't see the prinf message at the end of the main function.
Thanks for helping.
int readFileDesc = 0, writeFiledesc = 0;
int sourceFile = 1, destFile = 2, bufferSize = 3, isOverwrite;
if (argc != 4 && argc != 5) {
printf("Invalid number of arguments\n");
printf("Usage:\n");
printf(" ex1 [-f] SOURCE DEST BUFFER_SIZE");
exit(EXIT_FAILURE);
}
//Checking if -f [OP] is activated.
isOverwrite = (strcmp(argv[1], "-f") == 0);
if (isOverwrite) {
sourceFile++;
destFile++;
bufferSize++;
}
//Opening the source file
readFileDesc = open(argv[sourceFile], O_RDONLY);
if (readFileDesc < 0) {
perror("Unable to open source file for reading: ");
exit(EXIT_FAILURE);
}
//opening the destination file
if (!isOverwrite) {
//Case we dont have the -f [op] so we create the file.
writeFiledesc = open(argv[destFile],
O_CREAT | O_EXCL | O_WRONLY ,
S_IRUSR | S_IWUSR);
if (writeFiledesc < 0) {
perror("Unable to open destination file for reading: ");
exit(EXIT_FAILURE);
}
} else {
//Case we have the -f [op] so we override existing file.
writeFiledesc = open(argv[destFile], O_RDONLY | O_WRONLY | O_TRUNC);
if (writeFiledesc < 0) {
perror("Unable to open destination file for writing: ");
exit(EXIT_FAILURE);
}
}
//Assume the buffersize is legal.
bufferSize = atoi(argv[bufferSize]);
char data[bufferSize];
int nread, nwrite;
while ((nread = read(readFileDesc, data, bufferSize)) > 0) {
if ((nwrite = write(writeFiledesc, data, nread)) != nread) {
printf("write problem: ");
}
}
// cant see this!
printf("File %s was copied to %s" , argv[sourceFile] , argv[destFile]);
//handling errors
close(sourceFile);
close(destFile);
return EXIT_SUCCESS;
}
This is wrong:
writeFiledesc = open(argv[destFile], O_RDONLY | O_WRONLY | O_TRUNC);
Using both O_RDONLY and O_WRONLY is wrong. You need to use O_RDWR.
Per the POSIX standard for open():
SYNOPSIS
#include <sys/stat.h> #include <fcntl.h>
int open(const char *path, int oflag, ...);
...
Values for oflag are constructed by a bitwise-inclusive OR of flags
from the following list, defined in . Applications shall
specify exactly one of the first five values (file access modes)
below in the value of oflag:
O_EXEC
Open for execute only (non-directory files). The result is unspecified if this flag is applied to a directory.
O_RDONLY
Open for reading only.
O_RDWR
Open for reading and writing. The result is undefined if this flag is applied to a FIFO.
O_SEARCH
Open directory for search only. The result is unspecified if this flag is applied to a non-directory file.
O_WRONLY
Open for writing only.
Any combination of the following may be used:
...
Also, read() and write() return ssize_t, not int.

Open() for output not creating file

I have this function that utilizes open to set i/o redirection:
void setOutput(char * buffer){
int file = open(buffer, O_WRONLY || O_CREAT, S_IWUSR);
if(file < 0){ printf("error opening %s for output\n", buffer); }
if(dup2(file, 1) < 0){ printf("error with dup2 opening %s for output\n", buffer); }
}
When I run it, it works fine for files that are already defined but returns -1 when it receives a non-created file. Not sure why
You need to change the following
int file = open(buffer, O_WRONLY || O_CREAT, S_IWUSR);
To
int file = open(buffer, O_WRONLY | O_CREAT, S_IWUSR);
Format :
int open( char *filename, int access, int permission );
access : Should be provided as a bit wise OR operator, that means using | not || which is logical OR

Cannot simulate the write() system call in C

I have written the following code to simulate the write() system call in C.
The program executes without errors, but the new content is not written to myfile.
What is the problem?
#include<stdio.h>
int main(int ac, char* av[])
{
int fd;
int i = 1;
char *sep = "";
if(ac < 1)
{
printf("Insuff arguments\n");
exit(1);
}
if((fd = open("myfile", 0660)) == -1)
{
printf("Cannot open file");
exit(1);
}
while(i<ac)
{
write(fd, av[i], strlen(av[i]));
write(fd, sep, strlen(sep));
i++;
}
close (fd);
}
you should check the return value of write and see what's going on with perror (for exemple),
anyway you are not calling open in the correct way
try
if ((fd=open("myfile", O_WRONLY | O_CREAT, 0660))==-1)
{
printf("Cannot open file");
exit(1);
}
while(i<ac)
{
write(fd,av[i],strlen(av[i])); //check the return value of write
write(fd,sep,strlen(sep));
perror("write");
i++;
}
close (fd);
and include unistd.h fcntl.h
You need to specify mode(read or write) of the open when you are opening a file. In your open call you didn't specify any mode and you are giving file permission flags. For more information refer manual page of open system call.
You can try this in open call
fd=open("myfile", O_WRONLY | O_CREAT, 0660);
check return value of your write call, it is failing because you didn't specify any mode and you are trying to write data in to that file.

File Descriptors, open() returns zero

i open a file and want to write something in it. The problem is that the fd2 for some reason is 0. Instead of writting in the file, it writes on terminal. I dont close(0) anywhere in my code. Why do i get fd = 0 and not for example 3. The reason that writes on terminal is that the value of fd is zero? I know that fd = 0 is for standard input,
Any Ideas? Thank you.
if ((fd2 = open(logFile, O_RDWR |O_APPEND | O_CREAT , 0666) == -1))
DieWithError("open() failed");
printf("FD2 = %d",fd2); //returns me zero
bzero(tempStr, sizeof(tempStr));
bzero(hostname, sizeof(hostname));
gethostname(hostname, sizeof(hostname));
sprintf(tempStr, "\n%sStarting FTP Server on host %s in port %d\n", ctime(&currentime), hostname, port);
if (write(fd2, tempStr, strlen(tempStr)) == -1)
DieWithError("write(): failed");
Your conditional is off. Mind the parentheses. It should be:
if ((fd2 = open(logFile, O_RDWR |O_APPEND | O_CREAT , 0666)) == -1)
// ^^^ ^^^
Sometimes it might be best not to outsmart yourself:
int fd = open(...);
if (fd == -1) { DieWithError(); }
This is wrong.
if ((fd2 = open(logFile, O_RDWR |O_APPEND | O_CREAT , 0666) == -1))
You want this.
if ((fd2 = open(logFile, O_RDWR |O_APPEND | O_CREAT , 0666)) == -1)
It's hard to see because the line is so long, but the parentheses are in the wrong place. In short,
if (( fd2 = open(...) == -1 )) // your code
if (( fd2 = (open(...) == -1) )) // equivalent code
if (( (fd2 = open(...)) == -1) )) // correct code
If the line is so long, best to keep it out of the if...
#include <err.h>
fd2 = open(...);
if (fd2 < 0)
err(1, "open failed");

Resources