2014/08/15

簡單 Struct 清單的使用

這是一個簡單 Struct 的使用,資料餵入的方法只用單純的插入,暫時也還沒有遇到需求,所以就不寫搜尋跟刪除的功能了。

/**********
 * Define *
 * ********/

#define SLIST_ENTRY(s_type) struct s_type *next;

#define SLIST_IS_EMPTY(head) (head == NULL)

#define SLIST_NOT_EMPTY(head) (head != NULL)

#define SLIST_FOREACH(var, c_type, head) \
for (var=head; var!=NULL; var=var->next)

#define SLIST_INSERT(var, c_type, head) \
{
c_type *tail = head; \
var->next = NULL; \
if (NULL == tail) \
head = var; \
else \
{ \
while (tail && tail->next) \
tail = tail->next; \
if (tail) \
tail->next = var; \
} \
}

#define SLIST_FREE(c_type, head) \
if (head) \
{ \
c_type *this=head, *next; \
while (NULL != this) \
{ \
next = this->next; \
free(this); \
this = next; \
}; \
head = NULL; \
}

/***********
 * Example *
 * *********/

// Define Struct
typedef struct S_MyType
{
char FirstName[30];
char LastName[30];
SLIST_ENTRY(S_MyType);
} C_MyType;

// Define variable
C_MyType *Users;

// Insert Element
C_MyType *ptr = (C_MyType *)malloc(sizeof(C_MyType));
if (ptr)
{
ENSURE_ZERO(ptr, sizeof(C_MyType));
sprintf(ptr->FirstName, "Aim");
sprintf(ptr->LastName, "Wang");
SLIST_INSERT(ptr, C_MyType, Users);
}

// Read all data
C_MyType *ptr;
int i = 0;

SLIST_FOREACH(ptr, C_MyType, Users)
{
printf("User No.%2d: %s %s", i++, ptr->FirstName, ptr->LastName);
}

// release memory
SLIST_FREE(C_MyType, Users);

2014/08/12

find_pid_by_cmdline

要寫一個送 kill 到指定程式的 code,所以先要弄出這個根據 command line 找到 pid 的 function
#include <dirent.h>

static int find_pid_by_cmdline(const char *cmdline)
{
DIR *dir;
struct dirent *entry;
char *name, *p;
char status[32];
char buf[1024];
FILE *fp;
int pid, i;

dir = opendir("/proc");
if (!dir)
return 0;

while (entry = readdir(dir)) {
name = entry->d_name;
if (!(*name >= '0' && *name <= '9'))
continue;

pid = atoi(name);
sprintf(status, "/proc/%d/cmdline", pid);
if ((fp = fopen(status, "r")) == NULL)
continue;

name = fgets(buf, sizeof(buf), fp);
fclose(fp);
if (name == NULL)
continue;

for (i=0; i<1024; i++) {
if (buf[i] == 0) {
if (buf[i+1] == 0) {
i = 1024;
} else {
buf[i] = ' ';
}
}
}

if (!strcmp(buf, cmdline)) {
closedir(dir);
return pid;
}
}
closedir(dir);

return 0;
}