Linux系统编程_课时70_线程函数打印错误信息

本文详细讲解了在C语言中如何使用pthread_create函数创建线程,并介绍了如何通过检查其返回值来判断线程创建是否成功。当线程创建失败时,使用strerror函数获取并打印具体的错误信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

课时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,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值