#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>
//#include<sys/exits.h>
int global = 22;
char buf[] = "the test content!/n";
void exit_check(int stat) //waitpid的作用是等待子進程退出並回收資源,同時通過WIFEXITED等宏調用可以檢測子進程退出狀態。
{
if(WIFEXITED(stat))
{
printf("exit abnormally!the signal code is:%d/n",WEXITSTATUS(stat));
}
else if(WIFSIGNALED(stat))
{
printf("exit abnormally!the signal code is:%d/n",WTERMSIG(stat));
}
}
int main()
{
int test = 0,stat;
pid_t pid;
if(write(STDOUT_FILENO,buf,sizeof(buf))!=sizeof(buf)) //相當於printf
{
perror("write error!");
}
printf("fork test!/n");
pid = vfork();
if(pid == -1)
{
perror("fork");
exit(0);
}
else if(pid == 0)
{
global++;
test++;
printf("global=%d test=%d Child,my PID is %d/n",global,test,getpid());
if(execl("/bin/ps","ps","-au",NULL)<0) //使用execv函數族
perror("execl error!");
printf("this message will never be printed!/n");
exit(0);
}
if(waitpid(pid,&stat,0)==pid)
{
exit_check(stat);
}
global += 2;
test += 2;
printf("global = %d test = %d Parent,my PID is %d/n",global,test,getpid());
exit(0);
}
waitpid()使用實例:
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
pid_t pc,pr;
pc = fork();
if(pc < 0)
{
printf("Error fork/n");
}
else if(pc == 0) //子進程
{
sleep(5); //子進程暫停5秒
exit(0); //子進程正常退出
}
else
{
do //循環測試子進程是否退出
{
pr = waitpid(pc,NULL,WNOHANG);
if(pr == 0) { //若子進程還未退出,則父進程不阻塞
printf("The child process has not exited/n");
sleep(1);
}
}while(pr == 0);
if(pr == pc){ //若發現子進程退出,打印相應情況
printf("Get child exit code: %d/n",pr);
}
else
{
printf("Some error occured./n");
}
}
}