Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

Linux 程式設計常用片段:時間處理、後台運行、看門狗與堆疊列印

一、取得時間

<sys/time.h> 是 Linux 系統的日期時間標頭檔,例如:

struct timeval tv;
gettimeofday(&tv, NULL);

<time.h> 是 C/C++ 的日期與時間標頭檔:

char strtime[1024] = {0};
time_t now;
struct tm *ptm;
time(&now);
ptm = localtime(&now);
sprintf(strtime, "%d%02d%02d%02d%02d%02d",
        ptm->tm_year+1900, ptm->tm_mon+1, ptm->tm_mday,
        ptm->tm_hour, ptm->tm_min, ptm->tm_sec);

二、開機後台運行

在命令後加上 & 即可讓程式在背景啟動:

/path/to/yourprogram &

三、看門狗腳本

每隔 5 秒檢查 CardPlatform 進程是否存在,不存在就拉起:

#!/bin/sh
echo "enter shell" >> /usr/local/zf/CardPlatform/log
while true;do
    count=`ps -e | grep CardPlatform|grep -v grep`
    if [ "$?" != "0" ];then
        echo "start " >> /usr/local/zf/CardPlatform/log
        echo ">>>>CardPlatform is not runing..."
        /usr/local/zf/CardPlatform/CardPlatform
    else
        echo "running " >> /usr/local/zf/CardPlatform/log
        echo ">>>>CardPlatform is runing..."
    fi
    sleep 5
done

四、列印呼叫堆疊

#include <execinfo.h>

FILE* fp = fopen("/home/3.txt","ab");
if(fp)
{
    void *bt[20];
    char **strings;
    size_t sz;
    sz = backtrace(bt, 20);
    strings = backtrace_symbols(bt, sz);
    for(int i = 0; i < sz; ++i)
        fprintf(fp,"%s\n", strings[i]);
    fclose(fp);
}

實務提醒:backtrace_symbols 回傳的記憶體需自行 free,且編譯時要加上 -rdynamic 才能看到完整的符號名稱。

Copyright © Linux教程網 All Rights Reserved