使用共享内存实现管 [英] Implementing pipe using shared memory

查看:115
本文介绍了使用共享内存实现管的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我采取使用共享内存的管道。
我应该写和触觉只有库,而不是的main()

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

我遇到一个问题:

让我们说这是的main()谁使用我的图书馆 shared_memory_pipe.h 某些用户的:

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]);
}

在这个例子中,我们看到,孩子将关闭这两个他FD的,但父亲是停留在一个无限循环,永远闭上了FD的。在这种情况下,我管应仍然存在(的情况相比,当所有写FD的被关闭,或者所有的阅读FD的关闭或全部关闭,所以管道应该死)。

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

正如我以前说过,我只写了图书馆,( shared_memory_pipe.h )。
因此,图书馆里面,我怎么能知道,如果一个叉()已取得?

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.

推荐答案

哪个code的部分负责关闭FD的?

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

如果它是用户的code则叉()不是你的问题。毕竟,主叫方可能会做一个的execve 来一个不同的程序(一种常见的使用匿名管道),这样你的库code现在已从历程,尽管在FD的仍然是开放的,所以没有办法可以搞定。

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.

如果你有一个库API关闭文件描述符,那么这就是你能做的一切。一个exec'ed程序不会无论如何打电话给你库。

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.

这篇关于使用共享内存实现管的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆