Temporary disabling child processes from parent terminal at runtime

徘徊边缘 提交于 2021-01-28 22:13:16

问题


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

I know that exist a standard way to do this by

  • make pipe,
  • fork, redirect STDOUT to that pipe,
  • select&read pipe /write to parent stdout at the some loop at different thread,
  • manually pause this loop when need

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.

What can i do?


回答1:


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

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.

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.



来源:https://stackoverflow.com/questions/35985261/temporary-disabling-child-processes-from-parent-terminal-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!