首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MacOS 10.12上的getopt

MacOS 10.12上的getopt
EN

Stack Overflow用户
提问于 2017-10-18 17:45:27
回答 1查看 778关注 0票数 0

我对getopt在MacOS 10.12上有一种奇怪的体验。以下示例:

代码语言:javascript
复制
#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 (如手册中所期望的那样)。我做错了什么吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-18 17:57:56

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

这一行:

代码语言:javascript
复制
while ((option = getopt(argc, argv, “p:c:“)) != 1)

应:

代码语言:javascript
复制
while ((option = getopt(argc, argv, “p:c:“)) != -1)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46816186

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档