每一个进程都有一个非负整数唯一的ID,叫做进程标识符PID.
下面我们就用linux内核提供的函数 getpid()函数编程实现获取进程的pid
首先通过man命令查看手册查看getpid()函数的使用。
CLC@Embed_Learn:~$ man getpidNAME getpid, getppid - get process identificationSYNOPSIS #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;} 运行结果: CLC@Embed_Learn:~$ gcc demo1.c CLC@Embed_Learn:~$ ./a.outpid of demo1 is :4199 CLC@Embed_Learn:~$ toptop - 16:44:05 up 3:26, 4 users, load average: 0.70, 0.21, 0.11Tasks: 331 total, 2 running, 329 sleeping, 0 stopped, 0 zombieCpu(s): 25.2%us, 0.6%sy, 0.0%ni, 74.2%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%stMem: 1905156k total, 1059532k used, 845624k free, 95496k buffersSwap: 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