我对getopt在MacOS 10.12上有一种奇怪的体验。以下示例:
#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 (如手册中所期望的那样)。我做错了什么吗?
发布于 2017-10-18 17:57:56
你想要的是-1,而不是正面的:
这一行:
while ((option = getopt(argc, argv, “p:c:“)) != 1)应:
while ((option = getopt(argc, argv, “p:c:“)) != -1)https://stackoverflow.com/questions/46816186
复制相似问题