如何从 execl 命令捕获输出 [英] How to catch the ouput from a execl command

查看:43
本文介绍了如何从 execl 命令捕获输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 execl 函数从 C 运行 Linux 进程.当我这样做时,例如:

I'm using the execl function to run a Linux process from C. When I do, for example:

int cmd_quem() { 
  int result; 
  result = fork();
  if(result < 0) {
    exit(-1);
  }

  if (result == 0) {
    execl("/usr/bin/who", "who", NULL);
    sleep(4); //checking if father is being polite 
    exit(1); 
  } 
  else { 
    // father's time
    wait();
  }

  return 0;
}

我在控制台上看到在终端上执行who"的结果.我想知道的是是否有任何函数可以捕获"命令的输出结果.我的意思是,如果有办法抓住这个:

I get on the console the result of doing "who" on the terminal. What I'd like to know is if there is any function to "catch" the output result from a command. What I mean is, if there is anyway to catch this:

feuplive tty5         2009-11-21 18:20

这是 who 命令产生的行之一.

Which is one of the lines resulting from the who command.

推荐答案

为此,您需要打开一个管道.然后用管道的写入端替换子级的标准输出,并从父级管道的读取端读取.喜欢这个修改后的代码版本:

To do this, you need to open a pipe. You then replace the child's stdout with the writing end of the pipe, and read from the reading end of the pipe in the parent. Like this modified version of your code:

int cmd_quem(void) {
  int result;
  int pipefd[2];
  FILE *cmd_output;
  char buf[1024];
  int status;

  result = pipe(pipefd);
  if (result < 0) {
    perror("pipe");
    exit(-1);
  }

  result = fork();
  if(result < 0) {
    exit(-1);
  }

  if (result == 0) {
    dup2(pipefd[1], STDOUT_FILENO); /* Duplicate writing end to stdout */
    close(pipefd[0]);
    close(pipefd[1]);

    execl("/usr/bin/who", "who", NULL);
    _exit(1);
  }

  /* Parent process */
  close(pipefd[1]); /* Close writing end of pipe */

  cmd_output = fdopen(pipefd[0], "r");

  if (fgets(buf, sizeof buf, cmd_output)) {
    printf("Data from who command: %s\n", buf);
  } else {
    printf("No data received.\n");
  }

  wait(&status);
  printf("Child exit status = %d\n", status);

  return 0;
}

这篇关于如何从 execl 命令捕获输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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