编写一个程序使用系统调用fork生成3个子进程,并使用系统调用pipe创建一个管道,使得这3个子进程和父进程公用同一管道进行信息通信。
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <strings.h>
main(){
int i, r, p1, p2, p3, fd[20];
char buf[50], s[50];
pipe(fd); //父进程建立管道
while((p1 = fork()) == -1); //创建子进程P1,失败时循环
if(p1 == 0){ //由子进程P1返回,执行子进程P1
lockf(fd[1], 1, 0); //加锁锁定写入端
sprintf(buf, "child process P1 is sending messages!\n");
printf ("child process P1!\n");
write(fd[1], buf, 50); //把buf中的50个字符写入管道
sleep(5); //睡眠5秒,让父进程读
lockf (fd[1], 0, 0); //释放管道写入端
exit(0); //关闭
}else{ //从父进程返回,执行父进程
while((p2 = fork()) == -1);
if(p2 == 0){
lockf(fd[1], 1, 0);
sprintf(buf, "child process P2 is sending messages!\n");
printf ("child process P2!\n");
write(fd[1], buf, 50);
sleep(5);
lockf (fd[1], 0, 0);
exit(0);
}else{
while((p3 = fork()) == -1);
if(p3 == 0){
lockf(fd[1], 1, 0);
sprintf(buf, "child process P3 is sending messages!\n");
printf ("child process P3!\n");
write(fd[1], buf, 50);
sleep(5);
lockf (fd[1], 0, 0);
exit(0);
}
wait(0);
if((r = read(fd[0], s, 50)) == -1){
printf ("can`t read pipe!\n");
}else{
printf ("%s\n", s);
}
wait(0);
if((r = read(fd[0], s, 50)) == -1){
printf ("can`t read pipe!\n");
}else{
printf ("%s\n", s);
}
wait(0);
if((r = read(fd[0], s, 50)) == -1){
printf ("can`t read pipe!\n");
}else{
printf ("%s\n", s);
}
exit(0);
}
}
}
结果: