我是错误处理方面的新手。在我的代码中,我需要测试函数的返回值并在发生错误时打印错误的描述。
为了保持代码的线程安全性,我必须使用strerror_r,但是使用起来有些困难。在以下代码中,发生错误号22(ret_setschedparam为22)。如何通过使用strerror_r打印错误号22的描述,即“无效参数”?
我认为这个原型(prototype)应该是我需要的正确的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。

最佳答案


请注意,这不是标准的strerror_r接口(interface),而是GNU扩展。
您可能希望使用-D_GNU_SOURCE构建程序,或者将#define _GNU_SOURCE 1添加到文件顶部以获取此原型(prototype)而不是标准原型(prototype)。
您也没有正确调用strerror_r。这个电话:

char *buf_setschedparam;
size_t size_setschedparam = 1024;

... strerror_r(errno, buf_setschedparam, size_setschedparam)
promise strerror_rbuf_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));

关于c - strerror_r的示例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63101684/

10-11 16:11