Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bad file descriptor

Tags:

I'm learning about file descriptors and I wrote this code:

#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h>  int fdrd, fdwr, fdwt; char c;  main (int argc, char *argv[]) {      if((fdwt = open("output", O_CREAT, 0777)) == -1) {         perror("Error opening the file:");         exit(1);     }      char c = 'x';      if(write(fdwt, &c, 1) == -1) {         perror("Error writing the file:");     }      close(fdwt);     exit(0);  } 

, but I'm getting: Error writing the file:: Bad file descriptor

I don't know what could be wrong, since this is a very simple example.

like image 418
Lucy Avatar asked Jun 05 '11 19:06

Lucy


People also ask

What is bad file descriptor?

In general, when "Bad File Descriptor" is encountered, it means that the socket file descriptor you passed into the API is not valid, which has multiple possible reasons: The fd is already closed somewhere. The fd has a wrong value, which is inconsistent with the value obtained from socket() api.

What is bad file descriptor in Python?

When you don't allow the code to perform the functions related to the file descriptors and the methods used, a Bad File Descriptor Error arises in Python, indicating the wrong way of implementing the code.

What is a file descriptor example?

A file descriptor is a number that uniquely identifies an open file in a computer's operating system. It describes a data resource, and how that resource may be accessed. When a program asks to open a file — or another data resource, like a network socket — the kernel: Grants access.


2 Answers

Try this:

open("output", O_CREAT|O_WRONLY, 0777) 
like image 173
patapizza Avatar answered Sep 19 '22 15:09

patapizza


I think O_CREAT alone is not enough. Try adding O_WRONLY as flag to the open command.

like image 27
RedX Avatar answered Sep 21 '22 15:09

RedX