将文件描述符从主进程传递给它的线程
passing file descriptors from the main process to its threads
我有一个关于文件描述符从进程进入线程的简单问题。我几乎可以肯定,但需要确认,如果文件描述符被视为普通整数,因此可以通过整数数组传递给进程线程,例如通过 pthread_create() 线程参数。谢谢
是的,文件描述符只是整数,因此可以像任何其他变量一样作为函数参数传递。它们仍将引用相同的文件,因为打开的文件由进程中的所有线程共享。
#include <pthread.h>
struct files {
int count;
int* descriptors;
};
void* worker(void* p)
{
struct files *f = (struct files*)p;
// ...
}
int main(void)
{
struct files f;
f.count = 4;
f.descriptors = (int*)malloc(sizeof(int) * f.count);
f.descriptors[0] = open("...", O_RDONLY);
// ...
pthread_t t;
pthread_create(&t, NULL, worker, &f);
// ...
pthread_join(t);
}
术语 "process" 的粗略定义可以是 "a memory space with at least one thread"。换句话说,同一进程中的所有线程共享内存 space.
现在,文件描述符基本上是引用属于进程的 table 中对象的索引。由于对象属于进程,线程在进程内部运行,线程可以通过索引("file descriptor").
引用这些对象
我有一个关于文件描述符从进程进入线程的简单问题。我几乎可以肯定,但需要确认,如果文件描述符被视为普通整数,因此可以通过整数数组传递给进程线程,例如通过 pthread_create() 线程参数。谢谢
是的,文件描述符只是整数,因此可以像任何其他变量一样作为函数参数传递。它们仍将引用相同的文件,因为打开的文件由进程中的所有线程共享。
#include <pthread.h>
struct files {
int count;
int* descriptors;
};
void* worker(void* p)
{
struct files *f = (struct files*)p;
// ...
}
int main(void)
{
struct files f;
f.count = 4;
f.descriptors = (int*)malloc(sizeof(int) * f.count);
f.descriptors[0] = open("...", O_RDONLY);
// ...
pthread_t t;
pthread_create(&t, NULL, worker, &f);
// ...
pthread_join(t);
}
术语 "process" 的粗略定义可以是 "a memory space with at least one thread"。换句话说,同一进程中的所有线程共享内存 space.
现在,文件描述符基本上是引用属于进程的 table 中对象的索引。由于对象属于进程,线程在进程内部运行,线程可以通过索引("file descriptor").
引用这些对象