Reputation: 23
I am having some trouble with file descriptors. The standard fd table on a POSIX-compliant system should, for each process, have stdin as 0, stdout as 1, and stderr as 2. Thereafter, file descriptors should be issued sequentially, so a request to open() a new file should return the file descriptor 3.
This does not happen on my system. Code which was working a few hours ago has ceased to do so. Because it is very long and messy code, I have written a quick example of the sort of thing I am seeing.
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
void main(int argc, char *argv[])
{
int fToWrite;
char *outFileName = "chuckles.txt";
if (fToWrite = open(outFileName,O_WRONLY|O_CREAT|O_TRUNC) < 0) {
fprintf(stderr,"error during open!: %s\n",strerror(errno));
exit(EXIT_FAILURE);
}
write(fToWrite,"kekeke",6);
fprintf(stderr,"fToWrite = %i\n",fToWrite);
close(fToWrite);
}
On my machine, after running this code, chuckles.txt is created, but nothing is written to it. To the console is printed:
kekekefToWrite = 0
Note that kekeke was not written to chuckles.txt, and that fToWrite, the file descriptor of the file I open()ed, is 0. But 0 is reserved for stdin. Likewise, if I try to fprintf to STDOUT_FILENO (which is the int 1) or STDERR_FILENO (which is 2), I get a segfault. In the main program I am trying to write, the program segfaults when I try to write() to STDOUT_FILENO. A few hours ago, the same code snippets would happily put letters on the console; I don't know what changed. I've rebooted, but I don't know what else to do about it.
Strangely, printf still works. I was under the impression that printf just wrote to whatever was in the fd table's #2 entry.
Upvotes: 2
Views: 452
Reputation: 239011
<
has higher precedence than =
, so you are assigning the result of open(outFileName,O_WRONLY|O_CREAT|O_TRUNC) < 0
to fToWrite
, which is either 0
or 1
.
So you end up writing to your terminal.
Upvotes: 0
Reputation: 27632
You need an extra pair of parentheses:
if ((fToWrite = open(outFileName,O_WRONLY|O_CREAT|O_TRUNC)) < 0) {
That's why fToWrite gets the value 0.
Upvotes: 2