1.system
int xx_system(const char* cmd)
{
if (!cmd)
return -1;
int res = 0;
int status = 0;
pid_t pid = vfork();
struct rusage info;
memset(&info, 0, sizeof(struct rusage));
if (pid == 0)
{
//printf("child run.\n");
execl("/bin/sh", "/bin/sh", "-c", cmd, (char*) NULL);
//printf("child finished.\n");
_exit(1);
}
else if (pid > 0)
{
for(;;)
{
res = wait4(pid, &status, 0, &info);//wait4 base waitpid,wait4 more advanced
if (res > -1)
{
res = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
break;
} else if (errno != EINTR)
break;
}
//printf("parent finished.\n");
}
else
{
res = -1;
}
return res;
}
xx_system("echo hello world!");
2.内存相关
#define ms_realloc(p, size) __ms_realloc(p, size, __FILE__, __LINE__)
#define ms_malloc(len) __ms_malloc((len), __FILE__, __LINE__)
#define ms_free(p) __ms_free(p, __FILE__, __LINE__)
#define ms_calloc(n, size) __ms_calloc(n, size, __FILE__, __LINE__)
#define ms_valloc(len) __ms_valloc((len), __FILE__, __LINE__)
void* __ms_realloc(void *ptr, unsigned int size, const char* file, int lineno)
{
void* p = realloc(ptr, size);
if(!p)
{
system("cat /proc/buddyinfo");
printf("[ERROR]file:%s line:%d malloc size:%d fail.\n", file, lineno, size);
system("cat /proc/buddyinfo");
sleep(2);
assert(p);
}
else
{
}
return p;
}
void* __ms_malloc(unsigned int size, const char* file, int lineno)
{
if(size <= 0)
return NULL;
void* p = malloc(size);
if(!p)
{
system("cat /proc/buddyinfo");
printf("[ERROR]file:%s line:%d malloc size:%d fail.\n", file, lineno, size);
system("cat /proc/buddyinfo");
sleep(2);
assert(p);
}
else
{
//memset(p, 0, size);
}
return p;
}
void __ms_free(void* p, const char* file, int lineno)
{
if (!p)
return;
free(p);
p = 0;
}
void* __ms_calloc(unsigned int n, unsigned int size, const char* file, int lineno)
{
if(n <= 0 || size <= 0)
return NULL;
void *p = calloc(n, size);
if(!p)
{
printf("[ERROR]file:%s line:%d calloc (%d)size:%d fail.\n", file, lineno, n, size);
sleep(2);
assert(p);
}
return p;
}
void* __ms_valloc(unsigned int size, const char* file, int lineno)
{
if(size <= 0)
return NULL;
void* p = valloc(size);
if(!p)
{
system("cat /proc/buddyinfo");
printf("[ERROR]file:%s line:%d valloc size:%d fail.\n", file, lineno, size);
system("cat /proc/buddyinfo");
sleep(2);
assert(p);
}
else
{
//memset(p, 0, size);
}
return p;
}
3.打印
#define msprintf(format, ...) \
do{\
char stime[32] = {0};\
time_to_string(time(0), stime);\
printf("[%s %d==func:%s file:%s line:%d]==" format "\n", \
stime, getpid(), __func__, __FILE__, __LINE__, ##__VA_ARGS__); \
}while(0)
void time_to_string(int ntime, char stime[32])
{
struct tm temp;
localtime_r((long*)&ntime, &temp);
snprintf(stime, 32, "%4d-%02d-%02d %02d:%02d:%02d",
temp.tm_year + 1900, temp.tm_mon + 1, temp.tm_mday, temp.tm_hour, temp.tm_min, temp.tm_sec);
}
demo: msprintf("##################### test ###############");