as we all know the exec() family function can only take the executable file to create a new process which replace the original one even the PID is the same to the original one, in contrast the fork funciton create a whole new process .the fork() function duplicates the current process , creating a new entry in the process table with many of the same attributes as the current process, the new process is almost identical to the original , executing the same code but with its own data space , environment , and file descriptors ,
#include <sys/types.h>
#include <unistd.h>
pid_t fok(void);
call to fork in the parent returns the PID of the new child process , the new process continues to execute just link the original , with the exception that in the child process the call to fork returns 0 ,and this allows both the parent and child to determine which is which .
and a typical code fragment using fork is
pid_t new_pid;
new_pid=fork();
switch(new_pid){
case -1:.........break;
case 0:..........break;/*child process*/
default:.....break;/*parent process*/
}
now show you an example about it:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
int main(){
pid_t num;
char * mes;
int n=0;
int n1=1;
int n2=1;
printf("hello , are you ready\n");
num=fork();
switch(num){
case -1:{
printf("error\n");
break;
}
case 0:{
mes="child";
n1=5;
n=5;
break;
}
default:{
mes="parent";
n2=3;
n=2;
break;
}
}
for(int i=0;i<n1;i++){
printf("%s--------%d\n",mes,getpid());
sleep(1);
}
for(int i=0;i<n2;i++){
printf("%s>>%d\n",mes,getpid());
sleep(1);
}
printf("\n");
for(int i=0;i<n;i++){
printf("%s---%d",mes,i);
sleep(1);
}
return 0;
}
and the result is as follows: