getopt on MacOS 10.12

时间:2017-10-18 17:45:28

标签: c++ macos

我在MacOS 10.12上遇到过getopt的奇怪体验。以下示例:

#include <sys/types.h>
#include <unistd.h>
#include <sys/event.h>
#include <sys/time.h>

#include <cstdlib>
#include <string>
#include <iostream>
#include <cstdio>

void print_usage_and_exit()
{
  std::cout << “usage: execute-command -p <pid> -c <command>\n”;
  exit(EXIT_FAILURE);
}

int main(int argc, char** argv)
{
  int option;
  pid_t parent = getppid();
  std::string command;
  opterr = 0;
  while ((option = getopt(argc, argv, “p:c:“)) != 1)
  {
    printf(“processing argument %d\n”, optind);
    switch (option)
    {
    case ‘p’:
      std::cout << “pid: ” << parent << “\n”;
      break;
    case ‘c’:
      command = optarg;
      std::cout << “command: ” << command << “\n”;
      break;
    default:
      printf(“%c, err: %d, optopt: %c\n”, option, opterr, optopt);
      print_usage_and_exit();
      break;
    }
  }
  return EXIT_SUCCESS;
 }

我正在使用clang++进行编译,然后像./test -c a -p 12一样运行,但这会导致打印使用情况。问题是getopt在解析所有参数而不是-1时返回?(正如手册页所预期的那样)。我做错了吗?

1 个答案:

答案 0 :(得分:1)

你想要-1,而不是正面的:

这一行:

while ((option = getopt(argc, argv, “p:c:“)) != 1)

应该是:

while ((option = getopt(argc, argv, “p:c:“)) != -1)