【问题标题】:Standard output and Pipe use in execexec 中的标准输出和管道使用
【发布时间】:2014-05-21 14:35:43
【问题描述】:

我在理解 UNIX 系统中正确使用管道时遇到问题。 我有一个创建子进程的主进程。子进程必须运行与父亲不同的程序,他必须进行一些操作,然后子进程必须将结果传达给父亲。 但是在子进程中,我必须在终端上打印这些操作的部分结果。 我正在尝试使用测试程序来做到这一点,但我现在有点卡住了。这是主要的测试程序

测试.C

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

int main(){

  int mypipe[2];
  pid_t pid;
  char readbuffer[6];

  pipe(mypipe);

  if((pid = fork()) == 0){
    close(mypipe[0]);
    dup2(mypipe[1], STDOUT_FILENO);
    execlp("./proc", "./proc", NULL);
  } else {

  wait(-1);
  close(mypipe[1]);
  read(mypipe[0], readbuffer, sizeof(readbuffer));
  printf("%s", readbuffer); 
  }
}

./proc 程序的 c 文件是这样的: 程序.C

#include <stdio.h>

int main(int argc, char* argv[]){

  printf("check\n");

  return 0;
}

使用此解决方案,proc 程序无法在终端上打印任何内容。如何使 proc 程序在终端和管道上打印,以便主程序可以从那里读取??? 谢谢!

【问题讨论】:

    标签: c exec fork pipe


    【解决方案1】:

    即使您将 stdout 重定向到父程序,您仍然可以使用 stderr。当您想打印到控制台时,只需调用 fprintf(stderr, ...) 而不是 printf(...)

    【讨论】:

    • 我可以用其他方式吗?
    【解决方案2】:

    如果您希望您的“proc”程序在终端打印日志/调试信息,您可以使用 fprintf 和 stderr:

    fprintf(stderr, "What you need to print\n");
    

    你还可以看到你的程序在哪里写,使用strace

    【讨论】:

      猜你喜欢
      • 2018-05-15
      • 1970-01-01
      • 1970-01-01
      • 2012-02-23
      • 2014-06-03
      • 1970-01-01
      • 2014-04-05
      • 2021-04-29
      • 1970-01-01
      相关资源
      最近更新 更多