分类: LINUX
2010-07-09 14:39:45
今天完成多进程实验。
熟悉fork,exec,waitpid等函数使用,和多进程编程的基本步骤。
实验源码来自华清远见
#include
#include
#include
#include
#include
int main(void)
{
pid_t child1, child2, child;
child1 =fork();//创建子进程1
if(child1 == -1)
{
printf("child1 fork error;\n");
exit(1);
}
else if(child1 == 0)//子进程1中调用execlp函数
{
printf("in child1: excute 'ls -l'\n");
if(execlp("ls", "ls", "-l", NULL) < 0)
{
printf("child1 excelp error\n");
}
}
else
{
child2 = fork();//父进程中创建子进程2
if(child2 == -1)
{
printf("child2 fork error\n");
exit(1);
}
else if(child2 == 0)//子进程2中暂停5秒
{
printf("in child2:sleep for 5 seconds and then exit\n");
sleep(5);
exit(0);
}
printf("in father process:\n");
child = waitpid(child1, NULL, 0);//阻塞式等待
if(child == child1)
{
printf("get child1 exit code\n");
}
else
{
printf("error occured!\n");
}
do
{
child = waitpid(child2, NULL, WNOHANG);//非阻塞式等待
if(child == 0)
{
printf("the child2 process has not exited!\n");
sleep(1);
}
}while(child == 0);
if(child == child2)
{
printf("get child2 exit code!\n");
}
else
{
printf("error occured!\n");
}
}
exit(0);
}
编译运行结果如下:
注:下面的创建方法是错误的
不能一下创建两个。而要在父进程内部创建一个,外部创建一个。具体原因不明。
#include
#include
#include
#include
#include
int main(void)
{
pid_t child1, child2, child;
child1 = fork();
child2 = fork();
if(child1 == -1)
{
printf("child1 fork error;\n");
exit(1);
}
else if(child1 == 0)
{
printf("in child1: excute 'ls -l'\n");
if(execlp("ls", "ls", "-l", NULL) < 0)
{
printf("child1 excelp error\n");
}
}
if(child2 == -1)
{
printf("child1 fork error;\n");
exit(1);
}
else if(child2 == 0)
{
printf("in child2: sleep 5 seconds and then exit\n");
sleep(5);
exit(0);
}
else
{
printf("in father process:\n");
child = waitpid(child1, NULL, 0);
if(child == child1)
{
printf("get child1 exit code\n");
}
else
{
printf("error occured!\n");
}
do
{
child = waitpid(child2, NULL, WNOHANG);
if(child == 0)
{
printf("the child2 process has not exited!\n");
sleep(1);
}
}while(child == 0);
if(child == child2)
{
printf("get child2 exit code!\n");
}
else
{
printf("error occured!\n");
}
}
exit(0);
}
结果: