- 3
- 0
- 约7.62千字
- 约 21页
- 2018-06-07 发布于江西
- 举报
lab Linux进程及并发程序设计 ..doc
华南师范大学实验报告
学生姓名?学????号??????
专????业?多媒体与网络技术?年级、班级????
课程名称实验项目实验类型???验证??设计?R?综合?实验时间??年?月日
实验指导老师?? 实验评分?????????????????????
#includestdio.h
main( )
{
int p; //存放子进程pid号
while( ( p=fork( ) ) ==-1); //创建子进程直到成功为止
if (p == 0) //返回值=0表示子进程返回
{
printf(The Child is running\n);
}
else //返回值0表示父进程返回
{
printf(The Parent is running\n);
}
}
3.使用gcc命令对bingfa.c进行编译:
4.多次使用./a.out执行该命令,查看结果:
输出:
The Parent is running
The Child is running
或者
The Child is running
The Parent is running
运行结果分析:
通过实验结果可看出,这是一个并发程序,子进程和父进程在不同的情况下先后出现的顺序可能不同,具有随机性。
编写一个并发程序(子先父后)
根据要求编写程序:
#includestdio.h
#include stdlib.h
main( )
{
int p; //存放子进程pid号
while( ( p=fork( ) ) ==-1); //创建子进程直到成功为止
if (p == 0) //返回值=0表示子进程返回
{
printf(The Child is running\n);
exit(0);
// 在子进程结束时调用exit(0),使子进程自我终止,并发终止信号给其父进程;
}
else //返回值0表示父进程返回
{
wait(0);
//父进程等待子进程终止,再执行下方程序
printf(The Parent is running\n);
}
}
使用gcc命令对Childfirst.c进行编译:
4.多次使用./a.out执行该命令,查看结果:
输出:
The Child is running
The Parent is running
运行结果分析:
从运行结果可看出此程序实现了父等子的功能,始终是子进程先执行。
从代码上看,是用wait(0)和exit(0)实现的,在子进程(p=0)运行后使用exit(0)终止进程,在父进程(p0)内容程序执行前加上wait(0),使父进程接收到子进程结束的信号后才执行内容程序,从而实现了后执行父进程的效果。
编写一个管道应用程序(父提供给子字符串)
根据要求编写程序:
#include sys/types.h
#include unistd.h
#include stdio.h //printf函数的头文件
#includestdlib.h //exit函数的头文件
#define LINESIZE 1024
int main(void)
{
int n, fd[2];
pid_t pid;
char line[LINESIZE];
if(pipe(fd)0) //调用pipe()函数建立管道;
{
printf(pipe error); //建立不成功则返回“pipe error,并退出;
exit(1);
}
if((pid=fork())0) //创建进程,创建不成功则返回fork error并退出
{
printf(fork error);
exit(1);
}
else if(pid0) //父进程的fork()返回
{
close(fd[0]); //关闭管道读指针;
w
原创力文档

文档评论(0)