简体   繁体   English

将输出从长时间运行的子进程重定向到父进程

[英]Redirecting output from long-running child to parent process

I have two executables - parent process and it's child process, running in a long mode (for example server etc). 我有两个可执行文件-父进程及其子进程,它们以长模式运行(例如服务器等)。 All I need is to redirect child's stdout and stderr to parent's process and write them to file or print to tty, don't matter now. 我需要做的就是将孩子的stdout和stderr重定向到父进程,并将它们写入文件或打印到tty,现在不要紧。

This is pretty straightforward task if we talking about simple child, but with long-running child with partial outputting it is a problem. 如果我们谈论简单的子级,这是非常简单的任务,但是对于长期运行的子级来说,部分输出是个问题。

For example let's look at popular solution with usage of pipe (error checking and other non-important parts omitted): 例如,让我们看一下使用pipe流行解决方案(错误检查和其他不重要的部分被省略):

parent.c 父母

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, const char *argv[])
{
  int link[2];
  pid_t pid;
  char str[4096];

  pipe(link);
  pid = fork();

  if (pid == 0) {
    dup2(link[1], STDOUT_FILENO);
    close(link[0]);
    execl("/path_to_bin/fast_child", "fast_child", (char *)0);
  }
  else 
  {
    close(link[1]);
    read(link[0], str, sizeof(str));
    printf("Pipe contents: %s\n", str);
    wait(NULL);
  }

  return 0;
}

fast_child.c fast_child.c

#include <stdio.h>
#include <unistd.h>

int main(int argc, const char *argv[])
{
  printf("I'm fast child\n");
  return 0;
}

Using this type of child process in excellent and non-problematic way to get str(out|err) in parent, but using this code as child cause problems of output disappearing in parent: 以出色且无问题的方式使用这种类型的子进程来在父级中获取str(out | err),但是将以下代码用作子级会导致输出在父级中消失的问题:

slow_child.c slow_child.c

#include <stdio.h>
#include <unistd.h>

int main(int argc, const char *argv[])
{
  for (;;)
  {
    printf("I'm slow child\n");
    sleep(1);
  }
  return 0;
}

I'm thinking about socket usage as problem solving solution but I'm sure that this is not so efficient way and Unix provides better tools to do this (as usual :) 我正在考虑将套接字使用作为解决问题的解决方案,但是我敢肯定这不是那么有效的方法,Unix提供了更好的工具来执行此操作(与往常一样:)

Thank you. 谢谢。

You need to flush your output from the child every now and then or the parent task won't see anything. 您需要不时地刷新孩子的输出,否则父任务将看不到任何东西。 use fflush(stdout) at appropriate points. 在适当的地方使用fflush(stdout) Or you could switch off the buffering on stdout, but that might have a performance impact on your child, as it will do a system call on each character written. 或者,您可以关闭stdout上的缓冲,但这可能会对您的孩子产生性能影响,因为它将对每个写入的字符进行系统调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM