Implementing pipe using shared memory

三世轮回 提交于 2019-12-12 01:43:33

问题


I'm implementing a pipe using shared memory. I should write and touch only the library, and not the main().

I encountered a problem:

Lets say this is the main() of some user who uses my library shared_memory_pipe.h:

#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).

As I said before, I write only the library, (shared_memory_pipe.h). So, inside the library, how can I know if a fork() has been made?

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.

Thanks ahead! Please ask if you need more information.


回答1:


Before any fork the parent can store the result of getpid() to a global pid_t pid_parent.

Than at a later point in time the process cann test against pid_parent using getpid() again.

If than getpid()'s result is different from pid_parent the process is at least one fork() away from the parent.




回答2:


Which part of the code is responsible for closing the fd's?

If it is the user's code then a fork() is not your problem. 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.

If you have a library API to close the FDs, then that's all you can do. An exec'ed program would not call your library anyhow.



来源:https://stackoverflow.com/questions/14400289/implementing-pipe-using-shared-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!