Linux进程的创建和父子进程同步,操作系统实验报告_Linux进程创建与通信.doc
操作系統實驗報告_Linux進程創建與通信
2011-2012學年第一學期
專 業:
班 級:
學 號:
姓 名:提交日期:2011年11月實驗二 Linux進程創建與進程通信
【實驗目的
1. 熟悉有關Linux系統調用;
2. 學習有關Linux的進程創建,理解進程創建后兩個并發進程的執行;
3. 通過系統調用wait()和exit(),實現父子進程同步;
4. 掌握管道、消息緩沖等進程通信方法并了解其特點和使用限制。
實驗內容
1. 父進程創建子進程
實現父進程創建一個子進程,返回后父子進程分別循環輸出字符串“The parent process.”及“The child process.”5次,每次輸出后使用sleep(1)延時一秒,然后再進入下一次循環。給出源程序代碼和運行結果。程序代碼:
main()
{
int p1,i;
while ((p1=fork())==-1);
if (p1>0)
for (i=0;i<5;i++)
{
printf("I am parent.\n");
sleep(1);
}
else
for (i=0;i<5;i++)
{
printf("I am child.\n");
sleep(1);
}
}
運行結果:
The parent process.
The child process.
The parent process.
The child process.
The parent process.
The child process.
The parent process.
The child process.
The parent process.
The child process.
2. 父子進程同步
修改上題程序,使用exit()和wait()實現父子進程同步,其同步方式為父進程等待子進程的同步,即:子進程循環輸出5次,然后父進程再循環輸出5次。給出源程序代碼和運行結果。程序代碼:
main()
{
int p1,i;
while ((p1=fork())==-1);
if (p1>0)
{
wait(0);
for (i=0;i<5;i++)
{
printf("I am parent.\n");
sleep(1);
}
}
else
{
for (i=0;i<5;i++)
{
printf("I am child.\n");
sleep(1);
}
exit(0);
}
}
運行結果:
I am parent.
I am parent.
I am parent.
I am parent.
I am parent.
I am child.
I am child.
I am child.
I am child.
I am child.3. Linux管道通信
編寫一個程序,實現以下功能。給出源程序代碼和運行結果。
(1)父進程使用系統調用pipe()創建一個無名管道;
(2)創建兩個子進程,分別向管道發送一條信息后結束;
子進程1發送:Child 1 is sending a message to parent!
子進程2發送:Child 2 is sending a message to parent!
(3)父進程從管道中分別接收兩個子進程發來的消息并顯示在屏幕上,父進程結束。兩個子進程發送信息沒有先后順序要求。
源程序代碼:
#include
#include
#includemain()
{
int p1,p2,fd[2];
char outpipe[50];
char inpipe1[50]="Child1 is sending a message to parent!";
char inpipe2[50]="Child2 is sending a messege to parent!";
pipe(fd);
while((p1=fork())==-1);
if (p1==0)
{
lockf(fd[1],1,0);
write(fd[1],inpipe1,50);
exit(0);
}
else
{
while((p2=fork())==-1);
if (p2==0)
{
lockf(fd[1],1,0);
write(fd[1],inpipe2,50);
exit(0)
總結
以上是生活随笔為你收集整理的Linux进程的创建和父子进程同步,操作系统实验报告_Linux进程创建与通信.doc的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: oracle登录时无效的参数,oracl
- 下一篇: linux执行jar包命令没有主清单熟悉