在运行时从父终端临时禁用子进程 [英] Temporary disabling child processes from parent terminal at runtime

查看:64
本文介绍了在运行时从父终端临时禁用子进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简报::有许多子进程的大型Linux应用程序,我需要这样的东西:

Brief: there is huge Linux application with many child processes, and I need something like that:

/* parent process, far from fork*/
suppress_child_output_to_parent_tty();

printf("important message");
/* huge piece of code */
printf("important message");

restore_child_output_to_parent_tty();

我知道存在一种通过

  • 制造管道,
  • 叉,将STDOUT重定向到该管道,
  • 选择并在不同线程的some循环中将管道/read写入父stdout
  • 在需要时手动暂停此循环

但是我不应该为此使用长寿命线程,我的应用程序作为具有多个多线程子代的几个实例工作,并且存在一些OS sheduler问题,实际上,我应该节省cpu线程.因此,我为块子STDOUT寻找一些优雅的OS功能.

But i should NO use long-live threads for that, my application work as several instances with many multi-thread childs, and there are some OS sheduler issues, really, i should to economize cpu threads. And so i look for some elegant OS facility for block child STDOUT.

我该怎么办?

推荐答案

这不可能直接实现:如果您 fork(),则子级的文件描述符指向相同的文件描述作为父母的.从操作系统的角度来看,父级访问文件描述符与子级访问文件描述符没有区别.有多种方法可以解决此问题(例如,通过将调试器附加到子级),但是它们确实很复杂.

This isn't directly possible: If you fork(), the child's file descriptors point to the same file descriptions as the parent's. From the operating system's point-of-view, there is no difference in the parent accessing the file descriptor and the child accessing it. There are ways to get around this (e.g. by attaching a debugger to the child), but they are really complex.

最简单的方法可能是暂停孩子并将其继续:

The simplest way is probably to suspend the child and the resume it:

kill(child, SIGSTOP);

printf("important message");
/* huge piece of code */
printf("important message");

kill(child, SIGCONT);

根据设计,孩子不可能忽略 SIGSTOP .当第一个 kill()调用成功时,您可以放心地认为孩子已停止.通过 SIGCONT 调用继续进行.请注意,根据设计,可能有另一个过程可以继续您的孩子,但您对此无能为力.

It is not possible for the child to ignore a SIGSTOP by design. When the first kill() call succeeds, you can safely assume that the child has stopped. It is continued by the SIGCONT call. Note that by design it is possible for another process to continue your child before you want to, but there isn't anything you can do about that.

请注意,如果停止孩子,则可能会收到 SIGCHLD ,具体取决于您配置信号处理程序的方式.确保正确配置了所有内容,并阅读了相应的文档.

Note that you may receive a SIGCHLD if you stop your child, depending on how you configured the signal handler. Make sure you configured everything correctly and read the appropriate documentation.

这篇关于在运行时从父终端临时禁用子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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