一、进程的概念
在操作系统中,进程是资源分配和调度的基本单位。每个进程都有一个唯一的进程标识符(Process ID,PID),用于在系统中唯一标识该进程。进程可以通过创建子进程来生成新的进程,并形成进程树的层次结构。
二、进程创建函数
#include <unistd.h> // 头文件
pid_t fork(void); // 函数原型
//返回值一共三种情况,在父进程中,fork的返回值是新创建的子进程的PID,
在子进程中fork的返回值是0,如果出现错误,返回值是负数。
三、进程号(PID)查询函数
getpid(); // 获得当前进程的PID
getppid(); // 获得当前进程的父进程的PID
四、例子程序
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
pid_t pid;
int i = 0;
pid = fork(); // 创建子进程
if (pid < 0)
{
printf("fork is error\n");
return -1;
}
else if (pid > 0)
{
printf("this is parent, parent pid is %d\n", getpid());
}
else if (pid == 0)
{
printf("this is child, child pid is %d, parent pid is %d\n", getpid(), getppid());
}
i++;
printf("i is %d\n", i);
return 0;
}