sort:C错误中的多字符选项卡

时间:2015-05-02 10:34:27

标签: c

我有错误的多字符标签`\'\'-k 10 -r -n log.txt'

int
main ()
{
    const char *sort[] = { "sort", "-t ' ' -k 10 -r -n log.txt", 0 };
    const char *awk[] = { "awk", "{print $10}", 0 };

  struct command cmd [] = { {sort}, {awk} };

  return fork_pipes (2, cmd);
}

退格如何在C中转义或纠正排序参数。

所有代码:

#include <unistd.h>

struct command
{
  const char **argv;
};

int
spawn_proc (int in, int out, struct command *cmd)
{
  pid_t pid;

  if ((pid = fork ()) == 0)
    {
      if (in != 0)
        {
          dup2 (in, 0);
          close (in);
        }

      if (out != 1)
        {
          dup2 (out, 1);
          close (out);
        }

      return execvp (cmd->argv [0], (char * const *)cmd->argv);
    }

  return pid;
}

int
fork_pipes (int n, struct command *cmd)
{
  int i;
  pid_t pid;
  int in, fd [2];

  /* The first process should get its input from the original file descriptor 0.  */
  in = 0;

  /* Note the loop bound, we spawn here all, but the last stage of the pipeline.  */
  for (i = 0; i < n - 1; ++i)
    {
      pipe (fd);

      /* f [1] is the write end of the pipe, we carry `in` from the prev iteration.  */
      spawn_proc (in, fd [1], cmd + i);

      /* No need for the write and of the pipe, the child will write here.  */
      close (fd [1]);

      /* Keep the read end of the pipe, the next child will read from there.  */
      in = fd [0];
    }

  /* Last stage of the pipeline - set stdin be the read end of the previous pipe
     and output to the original file descriptor 1. */  
  if (in != 0)
    dup2 (in, 0);

  /* Execute the last stage with the current process. */
  return execvp (cmd [i].argv [0], (char * const *)cmd [i].argv);
}

int
main ()
{
    const char *sort[] = { "sort", "-t ' ' -k 10 -r -n log.txt", 0 };
    const char *awk[] = { "awk", "{print $10}", 0 };

  struct command cmd [] = { {sort}, {awk} };

  return fork_pipes (2, cmd);
}

1 个答案:

答案 0 :(得分:0)

我假设字符串作为参数传递给exec函数之一?那么你不能将多个参数放在一个字符串中,因为exec会把它作为程序的一个参数。

exec的参数成为被调用程序中的argv数组,因此例如"-t ' ' -k 10 -r -n log.txt"将成为参数(例如{{ 1}})在被调用的程序中。你需要分开参数:

argv[1]