我在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时返回?
(正如手册页所预期的那样)。我做错了吗?
答案 0 :(得分:1)
你想要-1
,而不是正面的:
这一行:
while ((option = getopt(argc, argv, “p:c:“)) != 1)
应该是:
while ((option = getopt(argc, argv, “p:c:“)) != -1)