fork新建进程
#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);
}