课时70_线程函数打印错误信息
1、pthread_create函数返回值
成功,返回0;
失败,返回error number
;
注意与系统中的errno
不同,pthread_create
函数的error number
不能使用perror()
函数直接打印错误信息。
2、strerror函数获取线程创建失败错误信息
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <pthread.h> //线程对应的头文件
//回调函数,子线程要做的任务
void* myfun(void* arg)
{
//打印子线程的ID
printf("child thread id:%ld\n",pthread_self());
return NULL;
}
//主函数
int main()
{
//创建一个子线程
pthread_t pthid;
int ret = pthread_create(&pthid,NULL,myfun,NULL);
if(ret != 0)
{
printf("err number:%d\n",ret);
//打印错误信息,使用strerror函数
printf("%s\n",strerror(ret));
}
//打印父线程ID
printf("parent thread id:%ld\n",pthread_self());
//让父线程sleep两秒,保证子线程先结束,父线程后结束
sleep(2);
return 0;
}
3、strerror函数介绍
The strerror() function returns a pointer to a string that describes the error code passed in the argument errnum,