这是我的工作脚本:
#pragma link "/usr/lib64/mysql/libmysqlclient.so"
#pragma include "/usr/include/mysql"
#include <mysql.h>
#include <string.h>
#include "gwan.h" // G-WAN exported functions
//static MYSQL *conn = NULL;
typedef struct {
MYSQL *conn;
} data_t;
int main(int argc, char *argv[])
{
u64 start = getus();
data_t **data = (data_t**)get_env(argv, US_SERVER_DATA);
xbuf_t *reply = get_reply(argv);
my_bool my_true = true;
if(!data[0]) // first time: persistent pointer is uninitialized
{
data[0] = (data_t*)calloc(1, sizeof(data_t));
if(!data[0])
return 500; // out of memory
data[0]->conn = (MYSQL *)mysql_init(data[0]->conn);
mysql_options(data[0]->conn, MYSQL_OPT_RECONNECT, &my_true);
if(! data[0]->conn) {
xbuf_xcat(reply, "MySQL Error");
return(200);
}
if(! mysql_real_connect(data[0]->conn, "localhost", "root", "willow", "test", 0, NULL, 0)) {
return 500;
}
xbuf_cat(reply, "initialized data<br>");
}
if(mysql_ping(data[0]->conn) > 0) return 500; // Prevent G-WAN to crash
mysql_query(data[0]->conn, "DELETE FROM example");
for(int i =1; i< 10; i++) {
char sql[1024];
s_snprintf(sql, 1023, "INSERT INTO example (id, name, age) VALUES(%d, 'Olivier', 33)", i);
mysql_query(data[0]->conn, sql);
}
int count = 0;
// Query Database
mysql_query(data[0]->conn, "SELECT id, name, age FROM example");
MYSQL_RES *result = mysql_store_result(data[0]->conn);
MYSQL_ROW *row;
while ((row = mysql_fetch_row(result))) {
count++;
xbuf_xcat(reply, ": %s : %s : %s", row[0], row[1], row[2]);
xbuf_xcat(reply, "<br/>");
}
mysql_free_result(result);
xbuf_xcat(reply, "<br>%llUmicro seconds : %d<br/>", (getus()-start), mysql_field_count(data[0]->conn));
xbuf_xcat(reply, "MySQL Client Version: %d", mysql_get_client_version());
return 200;
}
所以现在即使 mysql 关闭,G-WAN 仍然存在,并且当 mysql UP 时脚本再次工作。希望它会帮助别人。