简体   繁体   English

C语言中的文件描述符

[英]File descriptors in C. Lugging them around vs static global

If I'm writing a library that uses a file descriptor for doing stuff, when should I return it from lib_init() for the higher layer code to use and pass to my lib_do_stuff() calls, and when can I leave it as a private "member" in my C library as a static global in .c file? 如果我正在编写一个使用文件描述符进行处理的库,那么何时应从lib_init()返回它以供更高层的代码使用并传递给我的lib_do_stuff()调用,何时可以将其保留为私有我的C库中的“成员”作为.c文件中的静态全局变量?

If I don't think the user of my library should have control or even access to the file descriptor, can I just leave it, much like in C++ it would just be private ? 如果我不认为我的库用户应该拥有控制权甚至不能访问文件描述符,那么我是否可以只保留它,就像在C ++中那样只是private

What are the downsides for doing it either way? 无论哪种方式,这样做都有什么弊端?

Expanding my suggestion with an example. 通过示例扩展我的建议。

Your library needs two (at least) header files: One public that the users of your library includes, and one private that you include only in your library source files. 您的库需要两个(至少)头文件:库用户包含的一个公共文件,以及仅包含在库源文件中的一个私有文件。

The public could be something like 公众可能像

#pragma once

// This is all that is needed to declare pointers to the internal structure
typedef struct internal_structure STRUCTURE;

// The public API of your library
STRUCTURE *lib_init(void);
void lib_cleanup(STRUCTURE *s);
...

Then you have the private header file 然后你有私有头文件

#pragma once

struct internal_structure
{
    int fd;
    // Other members as needed
    ...
};

// Possible function prototypes of private functions

Then in your library source files you include both the public and the private header files, and use STRUCTURE for the black-box structure: 然后在库源文件中同时包含公共和私有头文件,并对黑盒结构使用STRUCTURE

#include <stdlib.h>
#include "public.h"
#include "private.h"

STRUCTURE *lib_init(void)
{
    STRUCTURE *s = malloc(sizeof *s);
    s->fd = open(...);
    // Other initialization
    ...
    return s;
}

void lib_cleanup(STRUCTURE *s)
{
    // Other cleanup
    ...
    close(s->fd);
    free(s);
}

Then the users of your library includes only the public header file, and uses your well-defined API: 然后,库的用户仅包含公共头文件,并使用您定义良好的API:

#include "public.h"

int main(void)
{
    STRUCTURE *s = lib_init();
    ...
    lib_cleanup(s);
    return 0;
}

The public functions should all take STRUCTURE * as one of their arguments, typically their first argument, similar to the lib_cleanup function. 公用函数都应将STRUCTURE *作为其参数之一,通常是它们的第一个参数,类似于lib_cleanup函数。 The function can then use the structure and its members any way they want. 然后,该函数可以根据需要使用结构及其成员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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