先来看这样一个例子,利用fork调用execlp()函数来在Linux下实现ps或ls命令:
#include "sys/types.h"
#include "unistd.h"
#include "stdio.h"
#include "stdlib.h"
int main()
{
pid_t result;
result=fork();
//报错处理
if(result==-1)
{
printf("Fork Error\n");
}
//son
else if(result==0)
{//调用execlp()函数,相当于"ps -ef"
if((result=execlp("ps","ps",NULL))<0);
printf("son\n");
}
//father
else
{
if((result=execlp("ls","ls",NULL))<0);
printf("father\n");
}
}
一般来讲, 我们编写1个普通的c程序, 运行这个程序直到程序结束, 系统只会分配1个pid给这个程序, 也就就说, 系统里只会有一条关于这个程序的进程.
但是执行了fork() 这个函数就不同了.
fork 这个英文单词在英文里是