编写一个程序实现以下功能: (1)使用fork()创建进程。 (2)使用管道实现子进程和父进程之间的通信。

如题所述

编写一段程序,使用系统调用fork( )创建两个子进程。当此程序运行时,在系统中有一个父进程和两个子进程活动。让每一个进程在屏幕上显示一个字符;父进程显示字符“a”,子进程分别显示字符“b”和“c”。试观察记录屏幕上的显示结果,并分析原因。
〈程序〉
#include<stdio.h>
main()
{
int p1,p2;
if(p1=fork()) /*子进程创建成功*/
putchar('b');
else
{
if(p2=fork()) /*子进程创建成功*/
putchar('c');
else putchar('a'); /*父进程执行*/
}
}

<运行结果>
bca(有时会出现abc的任意的排列)

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

编制一段程序,实现进程的管道通信。使用系统调用pipe()建立一条管道线。两个子进程p1和p2分别向通道个写一句话:
child1 process is sending message!
child2 process is sending message!
而父进程则从管道中读出来自两个进程的信息,显示在屏幕上。

〈程序〉
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
int pid1,pid2;

main( )
{
int fd[2];
char outpipe[100],inpipe[100];
pipe(fd); /*创建一个管道*/
while ((pid1=fork( ))==-1);
if(pid1==0)
{
lockf(fd[1],1,0);
sprintf(outpipe,"child 1 process is sending message!");
/*把串放入数组outpipe中*/
write(fd[1],outpipe,50); /*向管道写长为50字节的串*/
sleep(5); /*自我阻塞5秒*/
lockf(fd[1],0,0);
exit(0);
}
else
{
while((pid2=fork( ))==-1);
if(pid2==0)
{
lockf(fd[1],1,0); /*互斥*/
sprintf(outpipe,"child 2 process is sending message!");
write(fd[1],outpipe,50);
sleep(5);
lockf(fd[1],0,0);
exit(0);
}
else
{
wait(0); /*同步*/
read(fd[0],inpipe,50); /*从管道中读长为50字节的串*/
printf("%s\n",inpipe);
wait(0);
read(fd[0],inpipe,50);
printf("%s\n",inpipe);
exit(0);
}
}
}
〈运行结果〉
延迟5秒后显示:
child1 process is sending message!
再延迟5秒:
child2 process is sending message!

附:我承认我是复制的 不过很符合题意~
温馨提示:答案为网友推荐,仅供参考
相似回答