2017-02-10 32 views
1

我有一個命令行程序,我希望允許用戶使用單獨的線程打印當前時間。我目前有這樣設置:創建pthread,將當前時間打印到命令行中

我得到用戶輸入,然後將其與字符串time進行比較。如果它們相等,我創建一個設置時間變量的新線程。

char currentTime[20]; 
if (strcmp(input, "time") == 0) { 
    pthread_t thread; 
    int rc = pthread_create(&thread, NULL, getTime, NULL); 
    if (rc) { 
      printf("ERROR; return code from pthread_create() is %d\n", rc); 
      exit(-1); 
    } 
} 

getTime功能:

void getTime() { 
    time_t rawtime; 
    struct tm * timeinfo; 
    time (&rawtime); 
    timeinfo = localtime (&rawtime); 
    sprintf(currentTime,"%s", asctime (timeinfo)); 
    printf("%s", currentTime); 
    pthread_exit(NULL); 
} 

我得到一個錯誤Abort trap 6從這個,但我不從並行線程得到任何錯誤,所以我不知道是什麼問題。這似乎是線程得到正確創建。

+0

你實際上是否在'input'中讀取任何內容? '即使你不需要傳遞任何參數給線程,getTime(){'應該是'void * getTime(void * arg){'根據'pthread_create()'的要求。 –

+0

'pthread'函數的簽名是:'void * getTime(void * arg)'所以你需要做的第一件事是糾正你的'getTime()'函數。 – user3629249

回答

1

getTime()函數什麼也沒有返回。

currentTime緩衝區太短。

試試這個:

#include <pthread.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 

static void * getTime(void * arg) { 
    time_t rawtime; 
    struct tm * timeinfo; 
    time (&rawtime); 
    timeinfo = localtime (&rawtime); 
    printf("%s", asctime (timeinfo)); 
    return NULL; 
} 

int main(int argc, char * argv[]) { 
    pthread_t thread; 
    int  rc = pthread_create(&thread, NULL, getTime, NULL); 
    if (rc) { 
     printf("ERROR; return code from pthread_create() is %d\n", rc); 
     exit(-1); 
    } 
    sleep(1); 
    return 0; 
} 

編譯並執行它:

$ gcc -Wall -o timeThread timeThread.c -lpthread 
$ ./timeThread 
Fri Feb 10 19:55:06 2017 
$ 

的時間是25個字符長。

注意sleep(1)指令等待線程執行。