linux 获取进程id 函数??

linux 获取进程id 函数??,第1张

linux C中,获取当前进程id 函数为getpid()

头文件:#include <unistd.h>

函数原型:pid_t getpid(void)

函数说明:getpid ()用来取得目前进程的进程id,许多程序利用取到的此值来建立临时文件, 以避免临时文件相同带来的问题。

返回值:目前进程的进程id

范例

#include <stdio.h>

#include <unistd.h>

main()

{

    printf("pid=%d\n", getpid())

}

执行:

pid=1494 /*每次执行结果都不一定相同 */

通过查看资料,发现一种比较简单的方法就是在代码中使用printf将当前线程的id打印出来。

而这也分成两种情况:

1. 如果是pthread,则使用,

#include <pthread.h>

pthread_t pthread_self(void)

2. 如果不是pthread,即是由内核创建的线程,则使用,

#include <sys/types.h>

pid_t gettid(void)

获取线程所在的进程的id,方法如下:

#include <sys/types.h>

#include <unistd.h>

pid_t getpid(void)

pid_t getppid(void)

所以,我们在代码中使用如下的语句打印:

printf("\ntid=%lu, pid=%lu\n", gettid(), getpid())

这样就能获取当前代码所在的线程和进程了。

根据打印出来的进程的pid,获取进程名的方法是:

ls -lh /proc/pid/exe

lrwxrwxrwx 1 root root 0 Jan 1 20:48 /proc/pid/exe ->...

sh-3.2#

查看thread id的方法有:

1. sh-3.2# ps -efL | grep process,

ps命令指定-L命令选项可以用来查看进程下所包含的所有线程。

2. sh-3.2# ls -l /proc/pid/task/

查看进程下当前有哪些task,这些task指的就是线程。

linux获取进程id和进程名称作为一个共享库,应该需要统计使用本库的各种应用程序的使用频率,使用方法等信息。才能针对主要应用做出更好的改进。

www.dnjsb.com

那么就需要记录调用者的进程id或者进程名称,并且保存下来。保存的动作可以采用共享内存,也可以采用文件,这个在下篇博文描述,本文描述如何获取进程id和进程名称。范例:#include

<stdio.h>#include

<unistd.h>#define

CFGMNG_TASK_NAME_LEN

256int

main(){

int

ret

char

ac_tmp[CFGMNG_TASK_NAME_LEN]

ret

=

cfgmng_get_taskname(ac_tmp,

CFGMNG_TASK_NAME_LEN)

if

(0

!=

ret)

{

printf(Call

cfgmng_get_taskname

fail./n)

return

-1

}

printf(The

running

task

name

is

%s./n,

ac_tmp)

return

0}int

cfgmng_get_taskname(char

*ac,

int

len){

int

count

=

0

int

nIndex

=

0

char

chPath[CFGMNG_TASK_NAME_LEN]

=

{0}

char

cParam[100]

=

{0}

char

*cTem

=

chPath

int

tmp_len

pid_t

pId

=

getpid()

sprintf(cParam,/proc/%d/exe,pId)/*

printf(cParam

=

%s./n,

cParam)*/

count

=

readlink(cParam,

chPath,

CFGMNG_TASK_NAME_LEN)/*

printf(count

=

%d./n,

count)*/

if

(count

<

0

||

count

>=

CFGMNG_TASK_NAME_LEN)

{

printf(Current

System

Not

Surport

Proc./n)

return

-1

}

else

{

nIndex

=

count

-

1

for(

nIndex

>=

0

nIndex--)

{

if(

chPath[nIndex]

==

'/'

)//筛选出进程名

{

nIndex++

cTem

+=

nIndex

break

}

}

}

tmp_len

=

strlen(cTem)

if

(0

==

tmp_len)

{

printf(Get

task

fail./n)

return

-1

}

if

(len

<=

tmp_len

+1)

{

printf(len(%d)

is

less

than

taskname(%s)'s

len./n,

len,

cTem)

return

-1

}

strcpy(ac,

cTem)

return

0}从上面的实验范例可以看出,主要使用的函数是getpid获取本进程的id,再到/proc/pid/exe

中去找到对应的进程名称。在/proc目录中有很多跟进程相关的东西,都可以用这种方法触类旁通地实现。


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/yw/8462870.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-16
下一篇2023-04-16

发表评论

登录后才能评论

评论列表(0条)

    保存