opc0de
opc0de

Reputation: 11767

Creating a thread in a SharedLibrary raises segmentation fault

I am very new to the linux OS so I am trying to design a shared library witch will start a thread i have the followin code :

  1. The function init_log doesn't raise a segmentation fault it doesn't display noting in the log though can some one tell me why ?

  2. The function pthread_create raises a segmentation fault i use derror() to print that in the log!


void __attribute__ ((constructor)) setup();

void init_log()
{
    setlogmask(LOG_UPTO(LOG_NOTICE));
    openlog("TRACKER",LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL1);
}

    void loop()
    {
        while (0 == 0)
        {
            syslog(LOG_NOTICE,"OK BOSS");
            sleep(1000);
        }
    }

    void setup()
    {
        pthread_t thread_id;
        init_log();
        syslog(LOG_NOTICE,"LIB LOADED"); // this doesn't display
        pthread_create(&thread_id,0,&loop,(void*)(NULL));
    }

COMPILER LINKER PARAMS

**** Build of configuration Debug for project gt_trackers ****

make all 
Building target: libgt_trackers.so
Invoking: GCC C Linker
gcc -shared -o "libgt_trackers.so"  ./main.o   
Finished building target: libgt_trackers.so

**** Build Finished ****

Upvotes: 0

Views: 501

Answers (2)

Jinghao Shi
Jinghao Shi

Reputation: 1087

Towards your first question. syslog doesn't print the log message directly to console. It writes to the file /var/log/message by default (at least in my case :-). You can use tail -f /var/log/messages to see your log message.

The LOG_CONS flag in openlog only means that

Write directly to system console if there is an error while sending to system logger.

More information about syslog can be found here

FYI, here is a blog post about linux log files

Upvotes: 0

Jay
Jay

Reputation: 24895

The function void loop() should be void *loop (void *)

and the call the pthread_create should be

pthread_create(&thread_id,0,loop,NULL); 

The prototype for pthread_create is as below. You should match the prototype of your loop function with "start_routine" mentioned below.

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                   void *(*start_routine) (void *), void *arg);

The other point is that, just providing the name of a function is sufficient to pass it's address. No need to add an & before it.

Link to Pthread Tutorial: https://computing.llnl.gov/tutorials/pthreads/

As pointed out by alk, no need to typecast "NULL" also. Thanks alk. : )

Upvotes: 2

Related Questions