【问题标题】:set errno by pthread_create() function (issue)通过 pthread_create() 函数设置 errno(问题)
【发布时间】:2014-09-09 08:59:45
【问题描述】:

我在 ubuntu 和嵌入式 linux(我们的项目芯片)上运行以下代码。但是输出不同。为什么在嵌入式 linux 上运行时线程 errno 为 0?我怎样才能获得相同的输出? pthread_create() 函数可以设置errno吗?

此外,我使用了 fork() 函数而不是 pthread_create() 函数。在这种情况下,我用 ubuntu 得到了相同的输出。 例如:

if (fork())
    print_message_function("foo");

ubuntu:

>>main errno: 2
>>thread errno: 2

嵌入式linux:

>>main errno: 2
>>thread errno: 0

使用 fork() 函数时嵌入 linux:

>>main errno: 2
>>thread errno: 2

#include <unistd.h>     /* Symbolic Constants */
#include <sys/types.h>  /* Primitive System Data Types */
#include <errno.h>      /* Errors */
#include <stdio.h>      /* Input/Output */
#include <stdlib.h>     /* General Utilities */
#include <pthread.h>    /* POSIX Threads */
#include <string.h>     /* String handling */
#include <time.h>

typedef struct str_thdata
{
    int thread_no;
    char message[100];
} thdata;

int createError(char *str)
{
    int retVal = 0;

    if (NULL == fopen("YOK", "r"))
    {
        printf(">>%s errno: %d\n",str, errno);
        retVal = -errno;
    }
    return retVal;
}

void print_message_function ( void *ptr )
{
    int retVal;
    thdata *data;
    data = (thdata *) ptr;

    retVal = createError("thread");

    while(1)
        ;

    pthread_exit(0);
}

int main()
{
int retVal = 0;
    pthread_t thread1;
    thdata data1;

    data1.thread_no = 1;
    strcpy(data1.message, "Hello!");


    /*if (fork())
        print_message_function("foo");
    */
    pthread_create (&thread1, NULL, (void *) &print_message_function, (void *) &data1);

    retVal = createError("main");
    while(1)
    {

    }

    pthread_join(thread1, NULL);

    exit(0);
}

【问题讨论】:

  • 你的print_message_function有错误的返回类型,它应该返回void*,并且不要将你传递给pthread_create的函数转换为void*,它应该是void*(*)(void*)而不是void*,所以如果您只是修复返回类型,则无需强制转换它。

标签: multithreading thread-safety pthreads fork errno


【解决方案1】:

pthread 函数返回错误值,但不设置errno。这可能是因为errno 在设计 pthread 时不是特定于线程的。

使用示例:

int err = pthread_create(...);
if(err) {
    fprintf(stderr, "pthread_create: (%d)%s\n", err, strerror(err));
    exit(EXIT_FAILURE);
}

【讨论】:

  • 感谢您的回答。但是我想在thread_create调用的print_message_function中设置errno。
  • @zafer-victory 我想在 print_message_function 中设置 errno 然后一定要这样做。
猜你喜欢
  • 2019-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-05
  • 1970-01-01
  • 1970-01-01
  • 2021-06-29
  • 2013-04-13
相关资源
最近更新 更多