1. 程式人生 > >fork新建進程

fork新建進程

結束 eat pes puts dpi print -1 process 進程

#include <sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>

int main()
{
pid_t pid; //記錄fork()的返回值,用於區別父子進程
char *Message; //用於記錄輸出信息
int LoopVal; //用於記錄父子進程的循環次數
int LoopVal1; //用於循環
int ExitCode;

printf("the new fork starting\n");
pid=fork(); //新建子進程
switch(pid)
{
case -1: //建立進程錯誤
printf("creat new fork error!");
exit(1);
case 0: //子進程
Message = "This is in the child process";
LoopVal = 7;
ExitCode = 25;
break;
default: //父進程
Message = "This is in the parent process,waiting the child finished........";
LoopVal = 5;
ExitCode = 15;
break;
}
for(LoopVal1=0;LoopVal1<LoopVal;LoopVal1++)
{
puts(Message);
sleep(1);
}
if(pid!=0) //父進程
{
int StateVal;
pid_t ChildPid;
ChildPid = wait(&StateVal); //用StateVal記錄狀態信息,wait返回的是子進程退出時,子進程的進程id。
printf("The child has finished with the PID of %d\n",ChildPid);
if(WIFEXITED(StateVal)) //如果子進程正常結束,它就取一個非零值
  {

    //宏WEXITSTATUS(StateVal)是如果子進程正常結束,該宏函數的值為0,否則為非零值,與WIFEXITED(StateVal)剛好相反。
     printf("the child process has exit with code %d\n",WEXITSTATUS(StateVal));

//如果WIFEXITED非零,它返回子進程的退出碼
}

else
printf("the child has terminated abnormally\n");
} //子進程非正常結束
exit(ExitCode);
}

fork新建進程