简体   繁体   中英

C program in Linux to read a file descriptor passed as a terminal argument

I've been looking into different discussions how to get the open file descriptors for a current process on Linux from ac program, but could not find the following example:

./sample 4</some_file 5<some_other_file

Is there any way to get those file descriptors in a sample.c program in this case. I found out that those redirections are not treated as command line arguments. Hope someone can help.

Ofcourse fds 4 and 5 are given just as example, I would like the program to find out which fds were open on execution.

Given sample is started by

./sample 4</some_file 5<some_other_file

this will provide file descriptors that can be used to access those files:

int fd_for_some_file = 4;
int fd_for_some_other_file = 5;

If you don't want to assume file descriptors are fixed values, don't assign the files to hardcoded descriptor values when you start your process.

Edit:

I would like the program to find out which fds were open on execution.

In general, I don't think you can.

If, however, your code to identify pre-opened file descriptors runs before any invocation of open , you may be able to just run through values greater than 2 to see what they are using OS-specific means. On Linux:

for ( int fd = 3; fd < fd_max; fd++ )
{
    sprintf( linkname, "/proc/self/fd/%d", fd );
    int rc = readlink( linkname, linkvalue, sizeof( linkvalue ) ); 
    if ( rc == 0 )
    {
         // found a file opened by calling process
    }
}

Yes, that's inherently racy for multithreaded programs. If you're using GCC, you can put the code in a function with __attribute__(( constructor )) and it will run before main() is called. But even that could identify files opened by other such functions as being passed by the parent process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM