目录
创建子进程
—fork函数
pid_t fork(void);
成功返回两次,在父进程中返回子进程pid,子进程中返回 0,失败返回 -1 并设置 errno
获取进程PID
—getpid函数
pid_t getpid(void); —— 获取当前进程PID
pid_t getppid(void); —— 获取父进程PID返回 pid
DEMO1-基本函数使用
使用fork函数创建子进程,getpid获取进程pid,getppid获取父进程pid。
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc,char **argv)
{
pid_t pid;
printf("The program is executing!\n"); //the current program execued informations
printf("===============================================\n");
pid = fork();
if(pid == -1){
perror("fork error"); //the child process failed to creat
exit(0);
}else if(pid > 0){
printf("This is father process:\n"); //father process
printf("return pid is child pid in father process = %d\n",pid); //child process pid
printf("father process pid = %d\n",getpid()); //getpid get current process pid
sleep(1);
}else if(pid == 0){
printf("===============================================\n");
printf("this is child process:\n"); //child process
printf("the child process pid = %d\n",getpid()); //child process pid
printf("my father process pid = %d\n",getppid());//getppid get chird of father pocess pid
printf("===============================================\n");
}
printf("process end!\n"); //
return 0;
}
DEMO2-循环创建子进程
使用fork函数循环创建多个子进程,并且被创建的子进程打印自己是第几个被创建的以及自己pid。
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#define CREATFORKNUM 10
int main(int argc,char **argv)
{
pid_t pid[CREATFORKNUM] = {0};
int i;
for(i=0;i < CREATFORKNUM; i++){
pid[i] = fork(); //creat child process
if(pid[i] == 0){
break;
}
sleep(1); //sequential execution
}
if(i == 10){
exit(0); //because 0-10 = 11,therefore i=10 exit
}else
printf("This is %dth created || my pid = %d\n",i+1,getpid()); //
return 0;
}