线程编程 pthread 问题集合

1  undefined reference to `pthread_create'
由于pthread 库不是 Linux 系统默认的库,连接时需要使用静态库 libpthread.a,所以在使用pthread_create()创建线程,以及调用 pthread_atfork()函数建立fork处理程序时,在编译中要加 -lpthread参数

例如:在加了头文件#include <pthread.h>之后执行 pthread.c文件,需要使用如下命令:    gcc thread.c -o thread -lpthread

这种情况类似于<math.h>的使用,需在编译时加 -m 参数。


pthread_create()和pthread_atfork()函数使用时应注意的问题:

#include <pthread.h>

void pmsg(void* p)
{
    char *msg;
    msg = (char*)p;
    printf("%s ", msg);
}

int main(int argc, char *argv)
{
    pthread_t t1, t2;
    pthread_attr_t a1, a2;
    char *msg1 = "Hello";
    char *msg2 = "World";

    pthread_attr_init(&a1);
    pthread_attr_init(&a2);
    pthread_create(&t1, &a1, (void*)&pmsg, (void*)msg1);
    pthread_create(&t2, &a2, (void*)&pmsg, (void*)msg2);

    return 0;
}

gcc thread.c
/tmp/ccFCkO8u.o: In function `main':
/tmp/ccFCkO8u.o(.text+0x6a): undefined reference to `pthread_create'
/tmp/ccFCkO8u.o(.text+0x82): undefined reference to `pthread_create'
collect2: ld returned 1 exit status


2  strerror问题
头文件  
#include <error.h>

该文件定义了errno (即error number)对应的数值得含义.

在单线程程序中, errno在error.h中定义为一个全局变量 int. 在多线程程序中, 只要有_REENTRANT宏, errno被扩展为一个函数, 每个线程都有自己局部存储的errno. 总之, 在Linux中errno是线程安全的, 每个线程都有自己的错误码,放心使用.

strerror(errno) 顾名思义, 就是把错误码转换为有意义的字符串.  

perror("your message") 在打印完你自己的错误信息your message后, 会把错误码对应的字符串信息也打印出来, 即:printf("your message"), then strerror(errno)  所以, perro最好使, 很好,很强大~~


#include <stdio.h>   // void perror(const char *msg);
#include <string.h>  // char *strerror(int errnum);
#include <errno.h>  //errno


errno 是错误代码,在 errno.h头文件中;
perror是错误输出函数,输出格式为:msg:errno对应的错误信息(加上一个换行符);
strerror 是通过参数 errnum (就是errno),返回对应的错误信息。

以下是测试程序:

--------------------------------------------------------------------

// p_str_error.c
// perror , strerror 函数 , errno 测试

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

int main(int argc, char *argv[])
{
 FILE *fp;
 char *buf;

 if( (fp = fopen(argv[1], "r")) == NULL)
 {
  perror("perror"); // 好方便
  errno = 12;
  printf("strerror: %s\n", strerror(errno)); //转换错误码为对应的错误信息
  exit(1);
 }
 perror("perror");
 errno = 13;
 printf("strerror: %s\n", strerror(errno));
 
 fclose(fp); 
 return 0;
}


输入一个存在的文件名,如:./a.out 111

open失败则会输出:
perror: No such file or directory
strerror: Cannot allocate memory

open成功则会输出:
perror: Success
strerror: Permission denied

很明显,perror信息是由 perror函数输出的了,第二行是 strerror通过将 errno 轮换成对应的错误信息打印出来。

你可能感兴趣的:(线程编程 pthread 问题集合)