进程标识符pid
类型pid_t(传统意义上来讲是有符号的十六位的整型数)
命令ps
进程标识(进程号)是顺次向下使用
getpid();//获得当前进程的进程号
getppid(); //获得父进程的进程号
----- get process identification
#include <sys/types.h>
#include <unistd.h>
pid_t getpid(void);
pid_t getppid(void);
进程的产生
fork()//执行一次返回两次
----------create a child process
#include <unistd.h>
pid_t fork(void);
描述:
fork() creates a new process by duplicating the calling process.//通过复制当前进程创建一个新的进程
fork之后父子进程的区别:
-
fork返回值不一样
-
父子进程的pid不同 ,ppid也不同
-
未决信号(还未响应的信号)和文件锁不继承
-
资源利用量清0
返回值:
On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately.
//fork后在父进程当中返回的是子进程pid,在子进程当中返回值是0,如果失败返回值为-1
例子:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
pid_t pid;
printf("[%d]:Begin!\n",getpid());
pid=fork();
if(pid < 0)
{
perror("fork()");
exit(1);
}
if(pid==0)//child
{
printf("[%d]:Child is working!\n",getpid());
}
else //parent