1. Use fork to create a child process (copy process image): the parent process uses fork to start the child process, and then the parent process and the child process run separately.
(1) Code:
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main(){
pid_t pid;
char *message;
int n;
printf("fork progra starting\n");
pid=fork();
switch(pid){
case -1:
perror("fork failed");
exit(1);
case 0:
message="child";
n=5;
break;
default:
message="parent";
n=3;
break;
}
for(;n>0;n --)
{
puts(message);
sleep(1);
}
exit(0);
}
(2) Running results:
2. Waiting for a process: The result of the above experiment is rather confusing, let the parent process call the wait function to wait for the child process to end.
(1) Code:
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main(){
pid_t pid;
char *message;
int n;
int exit_code;
printf("fork progra starting\n");
pid=fork();
switch(pid){
case -1:
perror("fork failed");
exit(1);
case 0:
message="child";
n=5;
exit_code=37;
break;
default:
message="parent";
n=3;
exit_code=0;
break;
}
for(;n>0;n --)
{
puts(message);
sleep(1);
}
if(pid!=0) {
int stat_val;
pid_t child_pid;
child_pid=wait(&stat_val);
printf("Child has finished: PID=%d\n",child_pid);
if(WIFEXITED(stat_val))
printf("child exited with code %d\n", WEXITSTATUS(stat_val));
else
printf("child terminated abnormally\n");
}
exit(exit_code);
}
(2) Running results: