开发者

question on changing file descriptor number in c

开发者 https://www.devze.com 2022-12-10 05:17 出处:网络
my question is how would I change the program below so that it takes a file descriptor number on the command line rather tha开发者_StackOverflow社区n a file name?Any help would be greatly appreciated.

my question is how would I change the program below so that it takes a file descriptor number on the command line rather tha开发者_StackOverflow社区n a file name? Any help would be greatly appreciated. Thank You.

include "csapp.h"

int main (int argc, char **argv) 

{

    struct stat stat;
    char *type, *readok;

    /* $end statcheck */
    if (argc != 2) {
        fprintf(stderr, "usage: %s <filename>\n", argv[0]);
        exit(0);
    }
    /* $begin statcheck */
    Stat(argv[1], &stat);
    if (S_ISREG(stat.st_mode))     /* Determine file type */
        type = "regular";
    else if (S_ISDIR(stat.st_mode))
        type = "directory";
    else 
        type = "other";
    if ((stat.st_mode & S_IRUSR)) /* Check read access */
        readok = "yes";
    else
        readok = "no";

    printf("type: %s, read: %s\n", type, readok);
    exit(0);
}
/* $end statcheck */


It's easy to do what you want. You would need to convert argv[1] from a string to an integer (using strtol) and then you would change the call from stat() to fstat(). If you don't care about verifying that the argument is actually a number (which is what a file descriptor is), you could simply change the stat() call to:

fstat(atoi(argv[1]), &stat);

That said, I have to ask, what is the purpose for this?


File descriptors should be considered unique for a process. Even stdin/out/err are totally different in a pipe for two separate processes, while having the same fd.

Of course there are many ways to create a new process, but if you use one which preserves your fd's, you won't pass them in a command line anyway.


Trying to do anything on a file descriptor that's not been opened from within your process or parent process won't work. The file descriptor is just unique within your process/parent process(es).


Because that an FD number is a per process (and might its children) property, so only when a parent process had own an fd of an openning file, a child (forked in general) could accept the inherited fd number as command parameter and use it; otherwise no way unless using well-known "STDOUT" or "STDERR" etc.

0

精彩评论

暂无评论...
验证码 换一张
取 消