【问题标题】:command prompt program: how to allow user to enter unix commands?命令提示符程序:如何允许用户输入 unix 命令?
【发布时间】:2013-02-08 10:25:42
【问题描述】:

我在编写一个显示命令提示符的 C 程序时遇到了麻烦(这里没问题),它允许用户输入 unix 命令然后显示结果。我尝试了很多东西,但我一年前才开始编程,除了显示命令提示符外,我什么也没去;我需要有关如何接受 unix 命令 + 显示其结果的帮助。

我唯一的限制是,我需要我的程序搜索路径环境变量中指定的目录并找到命令可执行文件的位置,而不是用户提供绝对路径。我也不明白如何执行此操作,但在线搜索告诉我最好使用“getenv() 访问 OS PATH 变量并适当地为用户提供的命令添加前缀”。有人可以帮我从这里出去吗?提前感谢您的帮助。

【问题讨论】:

标签: c unix command prompt


【解决方案1】:

试试popen(),可以在手册页中找到here

看看这个:

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

void write_netstat(FILE * stream)
{
          FILE * outfile;
          outfile = fopen("output.txt","w");
          char line[128];

          if(!ferror(stream))
          {
                    while(fgets(line, sizeof(line), stream) != NULL)
                    {
                              fputs(line, outfile);
                              printf("%s", line);
                    }
                    fclose(outfile);
          }
          else
          {
                    fprintf(stderr, "Output to stream failed.n");
                    exit(EXIT_FAILURE);
          }
}

int main(void)
{
          FILE * output;
          output = popen("netstat", "r");

          if(!output)
          {
                    fprintf(stderr, "incorrect params or too many files.n");
                    return EXIT_FAILURE;
          }

          write_netstat(output);

          if(pclose(output) != 0)
          {
                    fprintf(stderr, "Could not run 'netstat' or other error.n");
          }
          return EXIT_SUCCESS;
}

这会将netstat 打印到文件中。您可以对所有命令执行此操作。它使用popen()。我写它是因为我需要一个 netstat 的日志。

【讨论】:

  • 谢谢!我最终使用了 popen
  • 没问题。很高兴我能帮上忙!
猜你喜欢
  • 2016-10-12
  • 2019-04-18
  • 2023-03-25
  • 2013-03-28
  • 2015-07-22
  • 2021-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多