简体   繁体   English

使用共享内存实现管道

[英]Implementing pipe using shared memory

I'm implementing a pipe using shared memory. 我正在使用共享内存实现管道。 I should write and touch only the library, and not the main() . 我应该只编写和触摸库,而不是main()

I encountered a problem: 我遇到了一个问题:

Lets say this is the main() of some user who uses my library shared_memory_pipe.h : 可以说这是使用我的库shared_memory_pipe.h的某些用户的main()

#include "shared_memory_pipe.h"

int main() {
    int fd[2];
    shared_memory_pipe(fd);
    if (fork()) {
        while(1) {}
    }
    shared_memory_close(fd[0]);
    shared_memory_close(fd[1]);
}

In this example we see that child closes both of his fd's, but the father is stuck on an infinite loop, and never closes his fd's. 在此示例中,我们看到孩子同时关闭了两个父亲的父亲,但父亲陷入了无限循环,并且从不关闭父亲的父亲。 In this case my pipe should still exists (compared to a case when all writing fd's are closed, or all reading fd's are closed, or all are closed, so the pipe should die). 在这种情况下,我的管道仍将存在(与所有写入fd都已关闭,或者所有读取fd都已关闭,或者全部已关闭,因此管道应该死掉的情况相比)。

As I said before, I write only the library, ( shared_memory_pipe.h ). 如前所述,我只编写库( shared_memory_pipe.h )。 So, inside the library, how can I know if a fork() has been made? 因此,在库中,我如何知道是否已创建fork()

How can I know that there is another process who has a reading/writing end to my shared memory pipe, so I'll know to close/not close my shared memory pipe? 我怎么知道还有另一个进程对我的共享内存管道进行读/写操作,所以我知道要关闭/不关闭我的共享内存管道吗?

I heard something about a command who knows that there was a fork() or something like that, but I didn't find it and I don't know it. 我听到了有关某个命令的信息,该命令知道有一个fork()或类似的东西,但我没有找到它,我也不知道。

Thanks ahead! 谢谢你! Please ask if you need more information. 请询问您是否需要更多信息。

Before any fork the parent can store the result of getpid() to a global pid_t pid_parent . 在任何派生之前,父级可以将getpid()的结果存储到全局pid_t pid_parent

Than at a later point in time the process cann test against pid_parent using getpid() again. 在以后的某个时间点,该进程无法再次使用getpid()pid_parent进行测试。

If than getpid() 's result is different from pid_parent the process is at least one fork() away from the parent. 如果getpid()的结果与pid_parent不同, pid_parent该过程与父级至少有一个fork()。

Which part of the code is responsible for closing the fd's? 代码的哪一部分负责关闭fd?

If it is the user's code then a fork() is not your problem. 如果是用户代码,那么fork()并不是您的问题。 After all, the caller could do an execve to a different program (a common use of anonymous pipes) so your library code is now gone from the process, even though the fd's are still open, so there is no way you can handle that. 毕竟,调用者可以对另一个程序执行execve (通常使用匿名管道),因此即使fd仍处于打开状态,您的库代码也已从该进程中删除,因此您无法处理它。

If you have a library API to close the FDs, then that's all you can do. 如果您有一个库API关闭FD,那么您就可以这样做。 An exec'ed program would not call your library anyhow. 执行程序不会以任何方式调用您的库。

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

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