分叉,执行->男人。无法正常工作
在这种情况下,我编写了一个简单的程序:
int main()
{
pid_t chpid;
chpid=fork();
if(chpid==0) // child
{
sleep(2);
execlp("/usr/bin/man","/usr/bin/man","ps",NULL);
printf("still alive\n");
}
else
{
printf("parent goes down\n");
}
return 0;
}
当运行父进程时死亡& 2 秒后我得到: /usr/bin/man: command exited with status 1: pager -s
为什么它会这样运行?肯定问题是父母的死亡,如果我在父母的代码中添加 while(1) 一切都很好。
我编写了一个测试程序,它每隔一段时间就将一些字符串写入标准输出。有用。看起来很奇怪。
In this case I wrote a simple prog:
int main()
{
pid_t chpid;
chpid=fork();
if(chpid==0) // child
{
sleep(2);
execlp("/usr/bin/man","/usr/bin/man","ps",NULL);
printf("still alive\n");
}
else
{
printf("parent goes down\n");
}
return 0;
}
While running parent dies & in 2 seconds i get: /usr/bin/man: command exited with status 1: pager -s
Why does it run this way? definitely the problem is the parent's death, if I add while(1) in parent's code everything is fine.
I wrote a test-prog that writes some string to standart output every period of time. It works. Seems strange.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通过在子进程运行时退出父进程,您刚刚对子进程进行了守护进程。守护进程及其分支没有控制终端,这是寻呼机运行的要求(我相信
pager -s
是less(1)
,但请检查一下:<代码>手册寻呼机)。另一方面,即使对于守护进程来说,仅写入 STDOUT 也不是犯罪,尽管不能保证任何人都会读取输出。
要获得更好的解释,请参阅 Richard Stevens 撰写的关于进程的“UNIX 环境中的高级编程”组、会话和控制终端。
By exiting from parent while child is running, you have just daemonized the child. Daemons and forks thereof do not have a controlling terminal, which is a requirement for pager to run (I believe
pager -s
isless(1)
, but check it:man pager
).On the other hand, just writing to STDOUT is no crime even for a daemon, although there's no guarantee anyone will be there to read the output.
For a better explanation, see "Advanced Programming in the UNIX Environment" by Richard Stevens on process groups, sessions, and controlling terminals.
使用
wait(3p)
等待子进程死亡。Use
wait(3p)
to wait for the child to die.所以。一些研究表明,shell 在启动我的进程后,通过
setpgid()
将控制终端设置为它(我的进程)。当它死掉时,shell 会再次调用setpgid()
,尽管所有子进程都被我的进程fork
了。所以它们已经是守护进程了。正如我发现的,守护进程也可以执行一些输出例程,但它们并不一定能成功。也许是,也许不是。这就是为什么孩子们在父母去世后仍然可以进行输出(例如,如果我分叉一个简单的周期性书写 hello world 程序)。人们明白他的输出将会出现问题并开始恐慌。我就是这么看的。至于
strace
,它非常简单:strace 在我的程序的整个生命周期中仍然存在,因此输出没有问题。So. A little research showed that the shell, having started my process, sets controlling terminal to it (my proc) by
setpgid()
. When it dies, the shell callssetpgid()
again despite of all the childs that werefork
'ed by my proc. So they are already daemons. As I found, daemons can do some output routines too, but they aren't definitely have success in it. Maybe yes, maybe no. That's why childs can still do output after their parent's death (for example if I fork a simple piriodical writong hello world program). And man understands that's smth is going to be wrng with his output and starts panic. That's the way I see it.As to
strace
, it's quite simple: the strace is still alive during all life cycle of my programs so there is no problem for thats output.