2017-10-18 111 views
0

我對MacOS 10.12上的getopt有着奇怪的體驗。下面的例子:MacOS上的getopt 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(從手冊頁預期)。難道我做錯了什麼?

回答

1

你想-1,而不是積極的:

這條線:

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

應該是:

while ((option = getopt(argc, argv, 「p:c:「)) != -1) 
+0

謝謝你,這麼愚蠢的錯字:)我猜它只是爲時已晚工作:D如果我可以的話,我會給這一千個贊成票:D –

+0

另外,我正要增加。 'getopt'不像你所說的那樣返回'?',它正確地返回'-1'。您的打印語句不知道如何將'-1'打印爲字符,因此它只是打印'?'。 – selbie

+0

公平點,謝謝。但是,再次將-1與1混合,我覺得很糟糕:D但我想我們都有這些時刻。 –