在嵌入式编程中通常在编写log文件时,需要获取本进程名称或路径写入log文件
-
#include <stdio.h>
-
#include <string.h>
-
#include <stdlib.h>
-
#include <unistd.h>
-
-
int main(int argc , char **argv)
-
{
-
char szlink[255], szpath[255];
-
-
sprintf(szlink, "/proc/%d/exe", getpid());
-
-
int ret;
-
ret = readlink(szlink, szpath, sizeof(szpath));//获取文件路径
-
if(ret < 0)
-
return-1;
-
else
-
{
-
printf("szpath:%s, len :%d\n", szpath, ret);
-
}
-
-
char *path_tmp;
-
-
path_end = strrchr(szpath, '/');
-
if(path_end == NULL)
-
return -1;
-
else
-
printf("path_tmp: %s \n",path_tmp);
-
-
char *name = path_tmp + 1;
-
printf("this process name is : %s in FUNCTION: %s\n", name, __func__);//打印此进程名称和所在的函数名称
-
return 1;
-
}
此程序是获取所在进程的名称,在写代码考虑到所有进程的适用性,就可以使用此方法将所在进程的名称获取。是个不错的选择哦!
-
#include <stdio.h>
-
#include <string.h>
-
#include <stdlib.h>
-
#include <unistd.h>
-
-
int main()
-
{
-
char szlink[255], szpath[255];
-
-
sprintf(szlink, "/proc/%d/exe", getpid());
-
-
int ret;
-
ret = readlink(szlink, szpath, sizeof(szpath));
-
if(ret < 0)
-
return-1;
-
else
-
{
-
printf("szpath:%s, len :%d\n", szpath, ret);
-
}
-
-
char *path_tmp;
-
-
path_end = strrchr(szpath, '/');
-
if(path_end == NULL)
-
return -1;
-
else
-
printf("pathend : %s szpath:%s, leftlen:%d \n",path_tmp,szpath, path_tmp - szpath);
-
-
-
char path[255] = {0};
-
strncpy(path, szpath, path_tmp - szpath);
-
printf("this process path is : %s in FUNCTION: %s\n", path, __func__);//打印此进程所在路径和所在的函数名称
-
return 1;
-
}
提供一个简单的方法,在log文件中可以用到哦,就是打印log文件时,有此进程的文件名和路径哦!
阅读(1661) | 评论(0) | 转发(0) |