Linux C++备忘录

一、单例模式、多线程之间的资源锁用法

test.h

#include <string>
#include <pthread.h>

using namespace std;

class Test
{
protected:
    pthread_rwlockattr_t _rwaddr;
    pthread_rwlock_t _rwlock;
protected:
    void rlock(){ pthread_rwlock_rdlock(&_rwlock); }    //多线程里互斥量读的时候要加该锁
    void wlock(){ pthread_rwlock_wrlock(&_rwlock); }    //多线程里互斥量写的时候要加该锁
    void unlock(){ pthread_rwlock_unlock(&_rwlock); }   //解锁

private:
    Test(void);
    ~Test(void);

    static Test * _cm;
public:
    static Test* getInstance();
};

#endif

test.cpp

#include "test.h"

Test *Test::_cm = NULL;

Test *Test::getInstance()
{
    if(NULL == _cm){
        _cm = new Test();
    }
    return _cm;
}

Test::Test()
{
    pthread_rwlockattr_init(&_rwaddr);
    pthread_rwlock_init(&_rwlock, &_rwaddr);
}

Test::~Test()
{
    pthread_rwlock_destroy(&_rwlock);
    pthread_rwlockattr_destroy(&_rwaddr);
}

二、程序运行参数

#include <getopt.h>

void GetOpt(int argc, char** argv, string& setupFilePath)
{
    if(argc<2)
    {
        cout<<"usage:-v for modul version!\n      -s for confPath!"<<endl;
        exit(-1);
    }
    const char * const short_options = "vs:";
    const struct option long_options[] = {{ "version", 0, NULL, 'v' },{ "setup", 1, NULL, 's' },{ NULL, 0, NULL, 0 }};
    int next_option;
    do{
        next_option = getopt_long (argc, argv, short_options, long_options, NULL);
        switch( next_option )
        {
            case 'v': /* -h or --help */
                cout<<_VERSION_<<endl;
                exit(0);
                break;
            case 's': /* -s or --setup */
                setupFilePath = optarg;
                break;
            case -1: /* Done with options. */
                break;
            default: /* Something else: unexpected. */
                exit(1);
                break;
        }
    }while( next_option != -1 );
}
如:

>test -v   可以查看程序版本号

>test -s test.conf   利用配置文件test.conf来运行程序等

三、捕捉kill消息

#include <getopt.h>

void sigRoutine(int sig)
{
    switch(sig)
    {
        case SIGUSR2:   //-12
            {
				dosomething();
                break;
            }
        case SIGUSR1:   //-10
            {
                cout<<"safe exit.";
                exit(0);
                break;
            }
        default:
            break;
    }
}

int main(int argc, char **argv) {
    ...
    signal(SIGUSR1,sigRoutine);
    signal(SIGUSR2,sigRoutine);
    signal(SIGPIPE,SIG_IGN);    //捕捉PIPE信号,防止向已关闭的连接中写数据时导致直接退出程序的情况。
    ...
    return 0;
}

如:

>kill -10 ID  程序安全退出

你可能感兴趣的:(Linux C++备忘录)