我是一个处理错误的新手;在我的代码中,我需要测试函数的返回值,并在发生错误时打印错误的描述。
为了保证代码线程的安全,我必须使用strerror_r,但我很难使用它。在下面的代码中,出现了错误号22 (ret_setschedparam为22)。如何打印错误号22的描述,即“无效参数”,使用R
我认为这个原型应该是我需要的正确的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。
发布于 2020-07-26 16:22:21
我认为这个原型应该是我需要的正确的strerro_r:
请注意,这不是标准的strerror_r接口,而是一个GNU扩展。
您可能希望使用-D_GNU_SOURCE构建您的程序,或者将#define _GNU_SOURCE 1添加到文件的顶部,以获得这个原型而不是标准的原型。
您也没有正确地调用strerror_r。这一呼吁:
char *buf_setschedparam;
size_t size_setschedparam = 1024;
... strerror_r(errno, buf_setschedparam, size_setschedparam)向strerror_r承诺,buf_setscheparam指向大小为1024的缓冲区。事实上,指针是未初始化的,所以一旦你让你的程序构建,它就会立即崩溃。
此外,pthread_*函数不设置errno,它们直接返回错误代码。
你想:
const size_t size_setschedparam = 1024;
char buf_setschedparam[size_setschedparam];
... sterror_r(ret_setschedparam, buf_setschedparam, size_setschedparam);甚至更好:
char buf[1024];
... sterror_r(ret_setschedparam, buf, sizeof(buf));https://stackoverflow.com/questions/63101684
复制相似问题