c - 如何将 dup2 与子进程一起使用?

标签 c linux

在我的 C 程序中,我正在创建一个子进程并在子进程中运行 execvp。但我正在尝试将错误消息更改为其他内容,用于 execvp 命令(如果有错误)。

我知道如果它返回,那就是一个错误,然后我可以在下一行打印我自己的自定义错误消息。这是一种可能发生的错误,例如,如果我将命令“sdfsd”提供给 execvp,就会发生这种情况。这部分对我有用。

但是如果我键入“find sdfsd”,它不会返回并打印“find: `sdfsd': No such file or directory”。

我想将此消息(基本上是来自 exevcp 的任何类型的错误消息)更改为我自己的自定义消息。

我相信我可以使用 dup2 来做到这一点,但我不确定如何...

在我试过的子进程中

dup2(STDERR_FILENO, 1); 
fclose(stderr);

但这只是阻止子进程写入任何错误消息。我仍然无法在所有情况下打印自己的消息..

有人知道怎么做吗? 谢谢

最佳答案

因为 execvp 如果它成功启动新程序就永远不会返回,你将无法在 execvp 运行程序后在子进程中打印你自己的错误消息> 失败。一种选择是将 stderr 通过管道传输到父进程,在那里拦截错误消息,然后打印您自己的错误消息。

例如:

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

int main(int argc, char **argv)
{
  int ff, p[2];
  FILE *f;
  char *vv[] = {"find", "garbage", (char *)NULL};
  char msg[100];

  if (pipe(p) != 0)
  {
    fprintf(stderr, "Pipe failed\n");
    return 1;
  }

  if ((ff = fork()) == -1 )
  {
    fprintf(stderr, "Fork failed\n");
    return 1;
  }

  if (ff == 0)
  {
    /* In the child process */
    close(2);
    close(p[0]);
    dup2(p[1], 2);
    execvp("find", vv);
    return 1;
  };

  /* In the parent process */
  close(p[1]);
  f = fdopen(p[0], "r");
  if (f == NULL)
  {
    fprintf(stderr, "Fdopen failed\n");
    return 1;
  }
  if (fgets(msg, sizeof(msg), f) == NULL)
  {
    fprintf(stderr, "Fgets failed\n");
    return 1;
  }
  printf("Error message was: %s", msg);
  /* and so on */
  return 0;
}

关于c - 如何将 dup2 与子进程一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14514446/

相关文章:

c - 有没有更好的方法来检查 pid 输入是否全是数字?

c - 将数组传递给 C 中的函数

linux - 在 Bash 中使用变量的值

java - 通过 bjdwp 在 Linux 上调试黑莓

c - 字符串文字和 strcat

c - 如何使用 scanf() 获取 int

linux - 通过R中变量的模糊匹配进行合并

linux - 将字符串替换为命令的输出,每次都不同

linux - 使用 awk 反转字段

c - SHGetFolderPath 无论如何都会返回 "C"?