0

I run below code on ubuntu and embedded linux(our project chip). But outputs are different. Why thread errno is 0 when run on the embedded linux? How can i get same output? Can pthread_create() function set errno?

Besides I used fork() function instead of pthread_create() function. In this instance, I got same outputs with ubuntu. for example:

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

ubuntu:

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

embeded linux:

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

embeded linux when fork() function used:

>>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);
}
  • your `print_message_function` has the wrong return type, it should return `void*`, and don't cast the function you pass to `pthread_create` to `void*`, it should be `void*(*)(void*)` not `void*`, so if you just fix the return type there's no need to cast it. – Jonathan Wakely Sep 09 '14 at 10:02

1 Answers1

4

pthread functions return the error value, but do not set errno. This is probably because errno was not thread-specific when pthreads were designed.

Usage example:

int err = pthread_create(...);
if(err) {
    fprintf(stderr, "pthread_create: (%d)%s\n", err, strerror(err));
    exit(EXIT_FAILURE);
}
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271