原理:
fork函数
子进程复制父进程
fork函数用于创建当前进程的子进程,创建子进程时,子进程会复制与父进程一样的堆栈段和数据段,和代码段。
例如:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid;
printf("Hello Ubuntu!");
pid=fork();
return 0;
}
其中可以看到我们代码中只写了一遍printf,结果却返回了两遍的printf,其实就是子进程复制父进程的数据,然后输出了一遍。
fork的返回值
fork的返回值,在不同进程中,返回的值不一样,在子进程中,是返回0,而在父进程是返回子进程的PID,如果返回的值小于0,则表示子进程创建失败。
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid;
printf("Hello Ubuntu!\n");
pid=fork();
if(pid<0)
{
return -1;
}else if(pid==0)//son
{
printf("I am son %d\n",pid);
}else
{
printf("I am parent %d\n",pid);
}
return 0;
}
在这里可以看到父进程的进程ID大于零(2999),子进程的进程ID为零,同时父进程是比子进程先执行完成的。
进程常用函数
获取当前进程的 PID函数_____getpid():
getpid函数没有参数,他返回一个
pid_t` 类型的值,即当前进程的进程 ID
例如:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid;
printf("Hello Ubuntu!\n");
pid=fork();
if(pid<0)
{
return -1;
}else if(pid==0)//son
{
printf("I am son %d\n",getpid());
}else
{
printf("I am parent %d\n",getpid());
}
return 0;
}
其中,这里的父进程和子进程返回各自的进程ID
父进程的PID函数_____getppid():
getppid函数与getpid函数大致一样,没有参数,返回一个
pid_t` 类型的值,即当前进程的父进程 ID
例如:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid;
printf("Hello Ubuntu!\n");
pid=fork();
if(pid<0)
{
return -1;
}else if(pid==0)//son
{
printf("I am son %d my parent %d\n",getpid(),getppid());
}else
{
printf("I am parent %d\n",getpid());
}
return 0;
}
在这里可以看到由getpid()函数得到的父进程的ID为3077,与在子进程里面用getppid()函数得到的父进程ID3077相同。
终止函数_____exit(int status):
1,status为返回退出的状态值,可以用wait获取此值
2,终止本进程
注:头文件为
#include <stdlib.h>
等待函数_____wait(int *status):
1,等待其中一个子进程结束:
①status参数,用于保存子进程结束状态的值
2,发出调用的进制只要有子进程,就会睡眠到子进程中,一个终止为止
3,如果调用成功,则返回子进程的进程ID,如果没有调用成功,则返回-1
注:头文件为:
#include <sys/wait.h>
例如:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main()
{
pid_t pid;
pid=fork();
if(pid==0)//son
{
printf("I am son %d my parent %d\n",getpid(),getppid());
exit(1);
}else if(pid>0)
{
int status=0;
printf("I am parent %d\n",getpid());
wait(&status);
}
return 0;
}
等待指定pid的进程结束_____waitpid(pid_t pid,int *status,int options):
①options使用WNOHANG参数,即使没有子进程退出,它也会立即返回,不会像wait那样永远等下去
②status参数,用于保存子进程结束状态的值
上锁函数_____lockf(fd,mode,size):
1,fd参数为文字描述字
2,mode参数为锁定方式,1为加锁,2为解锁
3,size参数为指定文件的位置,0表示从当前位置到文件尾