唐文阳吧 关注:4贴子:16
  • 0回复贴,共1

多线程代码

只看楼主收藏回复

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void)
{
int child1, child2, child;
//创建子进程1
child1 = fork();
if(child1 == -1){//子进程1的出错处理
printf("Child1 fork error\n");
exit(1);
}
else if(child1 == 0) //fork创建进程返回值为0说明现在是子进程
{
printf("In child1: execute 'ls -l'\n");
if(execlp("ls", "ls", "-l", NULL) < 0) //该函数的最后一个参数必须为NULL
{
printf("Child1 execlp error\n");
}
}
else{
child2 = fork();//在父进程中创建子进程2,然后等待两个子进程的退出
if (child2 == -1){//子进程2的出错处理
printf("Child2 fork error\n");
exit(1);
}
else if(child2 == 0){//在子进程2中使其暂停5s
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){ //由于子进程2未结束,waitpid()不阻塞而立即返回0,若结束,则返回子进程2的pid:child2,waitpid阻塞
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);
}


1楼2015-11-20 23:20回复