Section 4.2: wrong error reporting for pthread functions

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hello,

Throughout section 4.2 the following pattern is used for reporting
errors returned by various pthread functions:

if (pthread_func() == 0) {
    perror("pthread_func");
    exit(-1);
}

This is wrong, as pthread functions return the error number on failure
and do not set errno, as demonstrated by the following program, which
attempts to join with a detached thread:

#include <stdio.h>
#include <errno.h>
#include <pthread.h>

static void *
my_thread(void *arg)
{
    return NULL;
}

int
main()
{
    pthread_attr_t  attr;
    pthread_t       tid;

    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

    errno = 0;

    if (pthread_create(&tid, &attr, my_thread, NULL) != 0) {
        perror("pthread_create");
        return 1;
    }

    if (pthread_join(tid, NULL) != 0) {
        perror("pthread_join");
        return 1;
    }

    return 0;
}

The result:
# ./pthread_error
pthread_join: Success

The correct way to report errors is to use strerror() on the returned code:

#include <string.h>
...
    int rc;
    rc = pthread_join(tid, NULL);
    if (rc != 0) {
        fprintf(stderr, "pthread_join: %s\n", strerror(rc));
        return 1;
    }

# ./pthread_error
pthread_join: Invalid argument

Also, using exit(-1) is likely to produce unexpected results for the
parent process. Error codes returned from processes are small
integers, with the range being platform-specific. This means that -1
will get truncated to some unspecified value. It is customary to use 1
to indicate a failure from a process (if no other specific code is
defined). stdlib.h provides EXIT_SUCCESS and EXIT_FAILURE, which may
be easier to read.

--Elad
--
To unsubscribe from this list: send the line "unsubscribe perfbook" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at  http://vger.kernel.org/majordomo-info.html



[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[Index of Archives]     [Linux NFS]     [Linux NILFS]     [Linux USB Devel]     [Video for Linux]     [Linux Audio Users]     [Yosemite News]     [Linux Kernel]     [Linux SCSI]

  Powered by Linux