It can be done, but I've found tricks like this to be error-prone and non-portable in the past. You're much better off passing the file name instead, and let each program open its own descriptor. That said, here's what you can do, presuming you're on something unix-like.

Your C program has to use a file descriptor not used by the shell; let's say you use lucky seven:

int fd = open("/some/file", O_RDWR); dup2(fd, 7); close(fd);
Of course, you need to test that all the calls succeed.

With that, you can take advantage of the fact that fork will take along open file descriptors:

int pid = fork(); if (pid == 0) { execl("/the/perl/program", "program", "arg1", "etc"); _exit("URK!"); } close(7);
Again with tests inserted appropriate places.

In the Perl program, you take advantage of funny syntax in open being equivalent to a C fdopen, as documented in perlfunc:

open FH, '+<=7'; my $line = <FH>; # or whatever
This presumes the C program and the Perl program agree on file descriptor 7 being the "magic" one.

Note, I haven't tested this code; takes way too long to set up a reasonable test....


In reply to Re: Passing a filehandle from C to perl by VSarkiss
in thread Passing a filehandle from C to perl by suaveant

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.