2013-10-30 44 views
0

核心轉儲的錯誤,我知道這queston已被要求多次,但還是我無法算出這個段錯誤 - 在使用getopt的

#include<stdio.h> 
#include<getopt.h> 
int ch; 
int queue_time=60; 
int thread_num=4; 
char *scheduling_algo="FCFS"; 
extern char *optarg; 
int port=8080; 
int debug_flag,h_flag,l_flag; 
int main(int argc,char *argv[]) 
{ 
    while ((ch = getopt(argc, argv, "dhlprtns")) != -1) 
switch(ch) 
{ 
    case 'd': 
    debug_flag=atoi(optarg);  /* print address in output */ 
    break; 
    case 'h': 
    h_flag=atoi(optarg); 
    break; 
    case 'l': 
    l_flag=atoi(optarg);; 
    break; 
    case 'p': 
    port = atoi(optarg); 
    break; 
case 'r': 
    printf("%s",optarg); 
    break; 
case 't': 
    queue_time = atoi(optarg); 
    break; 
case 'n': 
    thread_num = atoi(optarg); 
    break; 
case 's': 
    scheduling_algo = optarg; 
    break; 
default: 
    printf("nothing was passed"); 
} 

    printf("%d",queue_time); 
    printf("%d",debug_flag); 
    printf("%d",h_flag); 
    printf("%d",l_flag); 
} 

我使用下面的命令

執行我的計劃
./a.out -d -h -l -t 55 

我收到核心轉儲錯誤。我在google上閱讀了幾個例子,但仍然面臨這個問題。任何人都可以幫忙嗎?

回答

7

你需要閱讀的getopt手冊頁()

while ((ch = getopt(argc, argv, "dhlprtns")) != -1) 
            ^^^^^^^^ 

這不符合您所使用的參數的方式。你 希望冒號「:」後面的標誌,期望參數。在你的代碼 「d」後面沒有冒號,但你似乎想它的價值:

case 'd': 
    debug_flag=atoi(optarg);  /* print address in output */ 
    break; 

所以發生的是,你在呼喚atoi(0),這是賽格斷層。

下面是手冊頁中的示例,請注意「b」後面的「f」是不是後跟冒號 。

#include <unistd.h> 
int bflag, ch, fd; 

bflag = 0; 
while ((ch = getopt(argc, argv, "bf:")) != -1) { 
     switch (ch) { 
     case 'b': 
       bflag = 1; 
       break; 
     case 'f': 
       if ((fd = open(optarg, O_RDONLY, 0)) < 0) { 
         (void)fprintf(stderr, 
          "myname: %s: %s\n", optarg, strerror(errno)); 
         exit(1); 
       } 
       break; 
     case '?': 
     default: 
       usage(); 
     } 
} 
argc -= optind; 
argv += optind; 
+0

非常感謝,手冊頁非常混亂。現在我得到了一個清晰的圖像。我只需要爲那些冒號的標誌使用optarg。 – user2934433

0

這可能是使用他人的事:如果你指定一個選項字母既沒有冒號,您也將獲得一個段錯誤,並用冒號如「dabcd:E」 - 在這種情況下,「d」與時並沒有冒號....然後使用該選項字母。

它看起來getopt及其變體不檢查此衝突並返回一個錯誤!