2017-10-18 1 views
0

MacOS 10.12에서 이상한 경험을했습니다. getopt. 다음 예 :getopt on 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 대신 (manpage에서 예상 한대로) 모든 인수를 구문 분석 할 때 ?을 반환한다는 것입니다. 내가 뭔가 잘못하고 있는거야?

답변

1

당신은 -1,하지가 긍정적 원하는 :

이 라인 :

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

가되어야한다

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

, 당신을 감사 바보 같은 오타 :) 내가 너무 늦기 그냥 추측 D : 제가 D : –

+0

일 수 있다면 이것에 1000 개의 upvote를 줄 것입니다. 'getopt'는 당신이 말한대로'? '를 반환하지 않습니다. 합법적으로'-1'을 리턴합니다. print 문은 '-1'을 문자로 인쇄하는 방법을 모르기 때문에 대신'?'를 출력합니다. – selbie

+0

공정한 의견, 고마워요. 하지만 다시 -1을 1로 섞으면 너무 기분이 좋지 않습니다. D 그러나 우리 모두는 그 순간을 가지고 있다고 생각합니다. –

관련 문제