6

有谁知道如何从execvp终端中捕获输出(我认为它的标准输出)而不是系统打印它(在 linux 上的 c 中)?

4

5 回答 5

6

execvp 替换内存中当前正在运行的进程。没有“捕捉”输出。

我怀疑您正在尝试从现有进程运行外部进程,并解析其输出。为此,您需要使用popen()which 执行 a fork()then an exec(),返回 aFILE *以读取(这将是stdout您刚刚运行的进程)。

于 2011-12-08T02:38:56.043 回答
4

我不信任popen/pclose,因为我在太多系统上工作过,SIGCHLD但处理方式略有不同。而且我不信任sh使用的 -shell 解析popen,因为我很少使用它。

Dave Curry撰写的 22 年历史的 O'Reilly 短书Using C on the UNIX System仍然是此类内容的很好参考

无论如何,这里有一些代码。它有点冗长,因为它将示例字符串解析"/bin/ls /etc"为数组{"/bin/ls", "/etc", 0}。但我发现在 98% 的情况下使用字符串格式更容易更短,尽管这个例子掩盖了这一点。

此代码生成/etc.您需要更改一些内容的列表,例如NUMBER()XtNumber(). 您需要确定它是否与您对SIGCHLD.

int main(void) {  // list the files in /etc
   char buf[100];
   FILE *fp;
   int pid = spawnfp("/bin/ls /etc", &fp);
   while (fgets(buf, sizeof buf, fp))
      printf("%s", buf);
   fclose(fp);                    // pclose() replacement
   kill(pid, SIGKILL);            // pclose() replacement
   return 0;
}

这里的子程序是:

static int spawnpipe(const char *argv[], int *fd) // popen() replacement
{
   int pid;
   int pipe_fds[2];

   if (pipe(pipe_fds) < 0)
      FatalError("pipe");

   switch ((pid = fork()))
   {
      case -1:
         FatalError("fork");
      case 0:                     // child
         close(1);
         close(2);
         dup(pipe_fds[0]);
         dup(pipe_fds[1]);
         close(pipe_fds[0]);
         close(pipe_fds[1]);

         execv(argv[0], (char * const *)argv);
         perror("execv");
         _exit(EXIT_FAILURE);    // sic, not exit()
      default:
         *fd = pipe_fds[0];
         close(pipe_fds[1]);
         return pid;
   }
}

这会将一个 ascii 字符串转换为一个argv列表,这对您来说可能没用:

Bool convertStringToArgvList(char *p, const char **argv, int maxNumArgs)
{
   // Break up a string into tokens, on spaces, except that quoted bits, 
   // with single-quotes, are kept together, without the quotes. Such  
   // single-quotes cannot be escaped. A double-quote is just an ordinary char.
   // This is a *very* basic parsing, but ok for pre-programmed strings.
   int cnt = 0;
   while (*p)
   {
      while (*p && *p <= ' ')    // skip spaces
         p++;
      if (*p == '\'')            // single-quote block
      {
         if (cnt < maxNumArgs)
            argv[cnt++] = ++p;   // drop quote
         while (*p && *p != '\'')
            p++;
      }
      else if (*p)               // simple space-delineated token
      {
         if (cnt < maxNumArgs)
            argv[cnt++] = p;
         while (*p > ' ')
            p++;
      }
      if (*p)
         *p++ = 0;               // nul-terminate
   }
   if (cnt < maxNumArgs)
      argv[cnt++] = 0;
   return cnt <= maxNumArgs;     // check for too many tokens (unlikely)
}

这会将参数字符串转换为标记,更重要的是,fd转换为 an fp,因为 OP 要求stdout

int spawnfp(const char *command, FILE **fpp)
{
   const char *argv[100];
   int fd, pid;
   if (!convertStringToArgvList(strdupa(command), argv, NUMBER(argv)))
      FatalError("spawnfp");
   pid = spawnpipe(argv, &fd);
   *fpp = fdopen(fd, "r");
   return pid;
}
于 2011-12-08T05:21:19.973 回答
1

请参阅 的文档popen,我认为这正是您所需要的。

于 2011-12-08T02:31:13.537 回答
1

正如其他人所说,popen是您想要使用的。像这样的东西...

#include <iomanip>
#include <iostream>

using namespace std;

const int MAX_BUFFER = 255;

int main()
{
        string cmd;
        cout << "enter cmd: ";
        cin >> cmd;
        cout << endl << "running " << cmd << "…" << endl;


        string stdout;
        char buffer[MAX_BUFFER];
        FILE *stream = popen(cmd.c_str(), "r");
        while ( fgets(buffer, MAX_BUFFER, stream) != NULL )
        stdout.append(buffer);
        pclose(stream);


        cout << endl << "output: " << endl << stdout << endl;
}
于 2011-12-08T02:38:32.903 回答
0

我找到了这个答案,它提供popen了一个execvp样式界面。

https://codereview.stackexchange.com/questions/31063/popen-with-array-of-arguments

于 2017-04-21T21:27:38.227 回答