0

I am getting an error when calling fdopen and it sets errno to 22. I am using the exec command to call a child process. The child calls fdopen on file descriptor 4. The first child works and sends data back to the parent and errno is 0. After the parent creates the next child process, fdopen(4, "w"); is called again which is when errno is set to 22.

From what I've read, errno 22 for fdopen() could mean mode argument is incorrect. I also read that it could be an error from fnctl and that could mean a bad file descriptor. I specify file descriptor 4 and it works on the first child process. Could that be why errno is being set to 22 when I try to create another FILE*?

I cannot figure out when it works for one child process but not the next. Can anyone shed some light on this for me?

Here is the code:

int main(int argc, char* argv[])
{
    cout << "Child " << argv[argc-1] << " starting" << endl;
    //close(3);
    if(argc < 1) fatal("Not enough arguments provided to ChildMain");
    int id = atoi(argv[argc-1]);
    //Child kid((int) *argv[1]);
    cout << "Error before fdopen(): " << errno << endl;
    FILE* out = fdopen(4, "w");
    if(out == NULL)
    {
        cout << "Child ID: " << id << endl;
        cout << "\tError: " << errno << endl << endl;
    }
    int ret = fprintf(out, "%d", id);
    fflush(out);
    return 0;
}
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
DFord
  • 2,352
  • 4
  • 33
  • 51
  • You should also display `strerror(errno)` – Basile Starynkevitch Jun 23 '12 at 06:24
  • You should not wire-in the `4` because the parent process (or even the grand parent) might have it already used. You should transmit explicitly file descriptors given by `pipe` syscall. Only file descriptors 0 (stdin), 1 (stdout), and 2 (stderr) are fixed. – Basile Starynkevitch Jun 23 '12 at 10:47

1 Answers1

1

For the first child process, the file descriptor's number is 4. For the second child process, 4 is in use in the parent, so it gets some other file descriptor number. The child is either going to have to search for the file descriptor or the parent will have to communicate it to the child in the environment, on the child's command line, or some other way.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • after i fork in the parent, i close file descriptor 4. So when the child sends data to the parent, it goes to the parents file desciptor 3 – DFord Jun 23 '12 at 02:28
  • Why 4? Where is 4 coming from? – David Schwartz Jun 23 '12 at 02:30
  • when pipe is called the first time, it returns file descriptors 3 and 4. The parent is supposed to read on 3 and the child is supposed to send data to the parent with file descriptor 4 – DFord Jun 23 '12 at 02:32
  • Right, and it works the first time. The problem is when `pipe` is called the *second* time. – David Schwartz Jun 23 '12 at 02:32