我有一个命令行程序,允许用户使用单独的线程打印当前时间。我现在设置成这样:
我获取用户输入,然后将其与字符串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);
    }
}

MygetTime功能:
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错误,但是pthread没有任何错误,所以我不确定问题是什么。似乎线程被正确创建了。

最佳答案

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)指令。

10-07 19:31
查看更多