欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

通过getpid()函数,获取进程标识符pid

程序员文章站 2022-06-24 20:35:09
...

通过getpid()函数,获取进程标识符pid

每一个进程都有一个非负整数唯一的ID,叫做进程标识符PID.
下面我们就用linux内核提供的函数 getpid()函数编程实现获取进程的pid

首先通过man命令查看手册查看getpid()函数的使用。

[email protected]_Learn:~$ man getpid
NAME
       getpid, getppid - get process identification

SYNOPSIS
       #include <sys/types.h>
       #include <unistd.h>

       pid_t getpid(void);
       pid_t getppid(void);

DESCRIPTION
       getpid()  returns  the  process  ID of the calling process.  (This is often used by
       routines that generate unique temporary filenames.)

       getppid() returns the process ID of the parent of the calling process.


代码如下:

#include <sys/types.h>
#include <unistd.h>
#include<stdio.h>

int main()
{
    pid_t pid;
    pid=getpid();
    printf("pid of demo1 is :%d \n",pid);//记得写\n   
    while(1);//让程序停在这里我们可以通过top指令,查看进程是否在运行
    return 0;
}

运行结果:

[email protected]_Learn:~$ gcc demo1.c 
[email protected]_Learn:~$ ./a.out
pid of demo1 is :4199 

[email protected]_Learn:~$ top
top - 16:44:05 up  3:26,  4 users,  load average: 0.70, 0.21, 0.11
Tasks: 331 total,   2 running, 329 sleeping,   0 stopped,   0 zombie
Cpu(s): 25.2%us,  0.6%sy,  0.0%ni, 74.2%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st
Mem:   1905156k total,  1059532k used,   845624k free,    95496k buffers
Swap:  5998588k total,        0k used,  5998588k free,   483784k cached

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND                        
 4199 CLC       20   0  4160  348  272 R  100  0.0   0:50.28 a.out                           
 2798 CLC        9 -11  418m 5956 4144 S    2  0.3   3:40.07 pulseaudio                      
 1404 root      20   0  203m  49m  11m S    1  2.6   0:56.34 Xorg                            
 2787 CLC       20   0 1166m  70m  35m S    0  3.8   1:01.21 compiz