简体   繁体   中英

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

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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