// return 0 is ok
int executesql(MYSQL *conn, const char *sql) {
    if(mysql_real_query(conn, sql, strlen(sql))) {
        sleep(20);
        conn = NULL;
        return 1;
    } else {
        return 0;
    }
}


//return 0 is ok
int init_mysql_conn(MYSQL *conn) {
    if(conn == NULL) {
        conn = mysql_init(NULL);

        const char timeout = 30;
        mysql_options(conn, MYSQL_OPT_CONNECT_TIMEOUT, &timeout);

        if(!mysql_real_connect(conn, host, username, password, db, port, 0, 0)) {
            sleep(2);
            return 1;
        } else {
            return 0;
        }
    } else {
        return executesql(conn, "set names utf8");
    }
}

MYSQL *conn;
init_mysql_conn(conn);

这样初始化的conn在查询的时候出现了段错误。
坑了好久才发现犯了c语言的一个低级错误,函数里面conn的指针变化了,但是要初始化的conn的指针还是原来的!

如果要改的话,可以改成如下:

//return 0 is ok
int init_mysql_conn(MYSQL **conn) {
    if(*conn == NULL) {
        *conn = mysql_init(NULL);

        const char timeout = 30;
        mysql_options(*conn, MYSQL_OPT_CONNECT_TIMEOUT, &timeout);

        if(!mysql_real_connect(*conn, host, username, password, db, port, 0, 0)) {
            sleep(2);
            return 1;
        } else {
            return 0;
        }
    } else {
        return executesql(*conn, "set names utf8");
    }
}

MYSQL *conn;
init_mysql_conn(&conn);

查了一下官方文档,似乎还有另一种初始化方式

MYSQL conn;
mysql_init(&conn);

Allocates or initializes a MYSQL object suitable for mysql_real_connect(). If mysql is a NULL pointer, the function allocates, initializes, and returns a new object. Otherwise, the object is initialized and the address of the object is returned. If mysql_init() allocates a new object, it is freed when mysql_close() is called to close the connection.

具体可查看官方文档