我是错误处理的新手;在我的代码中,我需要测试函数的返回值并在发生错误时打印错误描述。
为了保持代码线程安全,我必须使用 strerror_r,但我有一些难以使用的地方。在以下代码中,发生了错误编号 22(ret_setschedparam 为 22)。如何使用strerror_r打印错误号 22 的描述,即“无效参数” ?
我认为这个原型应该是我需要的正确 strerror_r :
char *strerror_r(int errnum, char *buf, size_t buflen);
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <sched.h>
#include <errno.h>
#include <string.h>
void *task();
int main()
{
pthread_attr_t attr;
struct sched_param prio;
pthread_t tid;
int ret_create;
int ret_setschedparam;
int ret_getschedparam;
int ret_join;
char *buf_setschedparam;
size_t size_setschedparam = 1024;
pthread_attr_init(&attr);
prio.sched_priority = 12;
ret_setschedparam = pthread_attr_setschedparam(&attr, &prio);
if (ret_setschedparam != 0) {
printf("Errore numero (pthread_attr_setschedparam): %s\n", strerror_r(errno, buf_setschedparam, size_setschedparam));
exit(EXIT_FAILURE);
}
ret_create = pthread_create(&tid, &attr, task, NULL);
printf("%d %d\n", ret_create, EPERM);
if (ret_create != 0) {
printf("Errore numero (pthread_create): %d\n", ret_create);
exit(EXIT_FAILURE);
}
ret_getschedparam = pthread_attr_getschedparam(&attr, &prio);
if (ret_getschedparam != 0) {
printf("Errore numero (pthread_attr_getschedparam): %d\n", ret_getschedparam);
exit(EXIT_FAILURE);
}
printf("Livello di priorità del thread: %d\n", prio.sched_priority);
ret_join = pthread_join(tid, NULL);
if (ret_join != 0) {
printf("Errore numero (pthread_join): %d\n", ret_join);
exit(EXIT_FAILURE);
}
return(0);
}
void *task()
{
printf("I am a simple thread.\n");
pthread_exit(NULL);
}
编译器给了我一个错误:它说 strerror_r 的输出是一个 int,而不是一个 char。