- 包含头文件
#include <sys/types.h>
#include <unistd.h>
- 函数原型
pid\_t getpid(void);
pid\_t getppid(void);
-
函数功能
- getpid() returns the process ID of the calling process. 获得当前进程的ID。
- getppid() returns the process ID of the parent of the calling process. 获得当前进程的父进程的ID。
-
函数参数
void
-
函数返回值
- getpid()返回当前进程ID
- getppid()返回当前进程的父进程ID
🥇2. fork()工作机制
🥈2.1 fork()的实现机制——一次调用两次返回与进程复制
下面通过一个案例来分析fork()是如何创建进程,又是如何返回的。
/\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
>File Name : fork\_test.c
>Author : Mindtechnist
>Company : Mindtechnist
>Create Time: 2022年05月18日 星期三 15时59分29秒
\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
int main(int argc, char\* argv[])
{
printf("=== process begin ===\n");
pid\_t pid = fork();
if(pid == -1)
{
perror("fork err");
return -1;
}
if(pid == 0) /\*子进程\*/
{
printf("i am child: %d, may parent: %d\n", getpid(), getppid());
/\* test2
while(1)
{
printf("fork process\n");
sleep(1);
}
\*/
}
if(pid > 0)
{
printf("i am call: %d, child: %d, parent: %d\n", getpid(), pid, getppid());
/\* test1
sleep(1);
\*/
/\* test2
while(1)