作为一个过程的孩子,怎么知道哪个文件描述符父母 [英] As a process child, how to know which file descriptor is parents

查看:211
本文介绍了作为一个过程的孩子,怎么知道哪个文件描述符父母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个程序,叉,等待他的孩子来完成,那么孩子确实在输入了一些工作,然后派生它的父不和等以同样的方式。

I am attempting to write a program which forks and waits for his child to finish, then the child does some work on an input and then forks the same way it's parent does and so on.

现在,我知道分叉复制到子文件描述的阵列,我应该关闭与母公司关联的人,但我不能找出哪些是父母。我需要给我的孩子是父母的pid?

Now, I know that forking copies to the child the array of file descriptors and that I should close the ones associated with the parent, but I can't figure out which are the parents. Do I need to give to my child it's parents pid?

我一直想换我的头周围一小时的大部分时间,我想我有某种头脑块的,因为我不能得出一个结论。

I've been trying to wrap my head around it for the better part of an hour and I think I have some kind of a mind block because I can't come to a conclusion.

TL; DR:作为一个孩子的过程我怎么知道哪些文件描述符属于我的父母

TL;DR: As a child process how do I know which file descriptors belong to my parent?

推荐答案

就在后叉(和的任何 EXEC 功能)您的孩子的过程具有相同的状态,它的父进程(除了,它只是在为0的结果儿童)。所以的你知道的哪些文件描述符,因为你有codeD在父母和放大器运行程序;孩子。在Linux上也可能会读的/ proc /自/ FD / 目录,看的 PROC(5)

Just after the fork (and before any exec function) your child process has the same state as its parent process (except for the result of the fork, which is 0 only in the child). So you know what are the file descriptors, since you have coded the program running in parent&child. On Linux you might also read the /proc/self/fd/ directory, see proc(5).

您可能会在后叉关闭最文件描述符前EXEC ;你可以code像

You might close most file descriptors after the fork and before the exec; you could code something like

for (int fd=3; fd<64; fd++) (void) close(fd);

我们是从3这是继 STDERR_FILENO 这是2投以(无效)开始,而且我们是在64擅自停止和关闭调用意味着我们不关心失败关闭读者....当然,如果你已经如一些管(7) -s父母和孩子之间的沟通你要小心避免关闭其相关的文件描述符(S)。

we are starting from 3 which is after STDERR_FILENO which is 2, and we are stopping arbitrarily at 64, and the cast to (void) on the close call means to the reader that we don't care about failing close.... Of course, if you have e.g. some pipe(7)-s to communicate between parent and child you'll be careful to avoid closing their relevant file descriptor(s).

(但是,做一个合闸回路像上面是口感不佳,老的方式)

在一般情况下,你会在你的程序设置最文件描述符的close-on-exec标志(如的上的fcntl(2) F_SETFD 运行和 FD_CLOEXEC 标记,或者直接开放(2)与 O_CLOEXEC ),那么的execve( 2)(在大多数子进程完成的后叉)将其关闭。

In general, you'll be careful in your program to set the close-on-exec flag on most file descriptors (e.g. fcntl(2) on F_SETFD operation and FD_CLOEXEC flag, or directly open(2) with O_CLOEXEC), then the execve(2) (done in most child processes after the fork) would close them.

这篇关于作为一个过程的孩子,怎么知道哪个文件描述符父母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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