Is there any way to safely and successfully write to a hand-picked file descriptor number, other than FD=0,1,2?

299 views Asked by At

My overall objective (motivation for the question):

To provide an executable ìo, from C/C++ compilation/linking, so that a user can execute it alternatively as:

  1. io 3> myout.txt. In this case myout.txt would contain whatever I explicitly send to FD=3 from within my code.

  2. io. In this case an error message is displayed indicating the user the need for 3> .... (Another option is simply losing that output, I still have to decide which is the best option).

I also need to be able to write to stdout/stderr at the same time.

As I see it, if I cannot tell the user "hey, the FD you have to redirect is #3", he cannot be certain he will actually capture the output. So, I conclude I have to hardcode FD=3 (wrong conclusion? how to achieve the objective otherwise?).

That was asked in Smart-write to arbitrary file descriptor from C/C++, and I am following here the indication of SO: "Your post has been associated with similar questions. If these questions don’t resolve your question, ask a new one." ... and here I am.

I admit to being frustrated by my inability to effectively convey my doubts, or otherwise to understand the comments. I could not find a solution to the description above, and this is hopefully a fruitful alternative attempt.


There are quite a few issues that were brought by this, and I asked a few related questions (listed at the bottom). Even if none of the questions received an answer, from the comments posted I ended up quite confused. In particular, I summarized here a specific fundamental question (and that is why I think this is not a dupe):

Can one write C/C++ code that safely and successfully writes to a hand picked file descriptor number, other than FD=0,1,2? (I guess this is the only way to satisfy the objective stated at the top). That would be something like

int main() {
    const int fd = 3;

and then writing to fd with either

    ssize_t nbytes = write(fd, ...

or

    FILE * fp = fdopen(fd, "a");  /* or some other mode */
    fprintf(fp, ...

(and there may be other ways).

In Smart-write to arbitrary file descriptor from C/C++, I posted code that included this usage, and comments posted suggested a way of completing code (even though I did not manage to make it work). In any case, it would be ok to use a hand picked fd number.

In Safety check prior to using fdopen, comments posted suggested I shouldn't ever use a hand picked fd number.

I am then confused about this.

My third related question is Correct way of using fdopen

0

There are 0 answers