日期:2014-05-16  浏览次数:20687 次

通过如下函数能否实现errno是线程安全的?
#include <stdio.h>
#include <pthread.h>
#include <stdio.h>
#include <pthread.h>
#include <errno.h>

static pthread_key_t key;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
pthread_mutex_t errno_mutex = PTHREAD_MUTEX_INITIALIZER;

static void
thread_init (void)
{
  pthread_create (&key, free);
}

int
__errno_s ()
{
  int errno_s;
  pthread_once (&init_done, thread_init);
  pthread_mutex_lock (&errno_mutex);
  pthread_setspecific (key, (void *)errno_s);
  //errno_s = pthread_getspecific (key);
  errno_s = errno;
  pthread_mutex_unlock (&errno_mutex);
  return errno_s;
}

int
main()
{
  FILE *fp;

  fp = fopen ("nofile", "w+");
  if (__errno_s () == 4)
  {
  printf ("failed to open file.\n");
  }
}

如果不行,如何尽可能简洁的将以前代码中用到errno的地方都变为线程安全的?

------解决方案--------------------
#define errno __errno_s()
------解决方案--------------------
问题没看清楚,上面是胡说八道......
------解决方案--------------------
支持线程的系统通常提供了线程安全的errno访问方法,直接使用即可!
INTRO(2) FreeBSD System Calls Manual INTRO(2)

NAME
intro -- introduction to system calls and error numbers

LIBRARY
Standard C Library (libc, -lc)

SYNOPSIS
#include <errno.h>

DESCRIPTION
This section provides an overview of the system calls, their error
returns, and other common definitions and concepts.

RETURN VALUES
Nearly all of the system calls provide an error number referenced via the
external identifier errno. This identifier is defined in <sys/errno.h>
as

extern int * __error();
#define errno (* __error())

The __error() function returns a pointer to a field in the thread spe-
cific structure for threads other than the initial thread. For the ini-
tial thread and non-threaded processes, __error() returns a pointer to a
global errno variable that is compatible with the previous definition.

When a system call detects an error, it returns an integer value indicat-
ing failure (usually -1) and sets the variable errno accordingly. (This
allows interpretation of the failure on receiving a -1 and to take action
accordingly.) Successful calls never set errno; once set, it remains
until another error occurs. It should only be examined after an error.
Note that a number of system calls overload the meanings of these error
numbers, and that the meanings must be interpreted according to the type
and circumstances of the call.

The following is a complete list of the errors and their names as given
in <sys/errno.h>.

------解决方案--------------------
mark
------解决方案--------------------
不用,直接使用就可以了!