学习笔记
使用创建n个子进程的模型,创建兄弟进程,使用循环因子i标示。注意管道的读写行为。
兄:ls -l
弟:wc -l
父:等待子进程回收
$cat brothercommunication.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<errno.h>
#include<sys/wait.h>
void sys_err(const char *str)
{
perror(str);
exit(1);
}
int main(int argc, char *argv[])
{
int fd[2];
int ret;
int i;
pid_t pid;
ret = pipe(fd);
if(-1 == ret)
{
sys_err("pipe error!");
}
for(i =0;i<2;i++) {
pid = fork();
if(pid == -1)
{
sys_err("fork error!");
}
if(0 == pid)
{
break;
}
}
if(2 == i)
{
wait(NULL);
wait(NULL);
}else if( 0 == i)//xiong
{
close(fd[0]);
dup2(fd[1],STDOUT_FILENO);
execlp("ls","ls","-l",NULL);
sys_err("execlp error!");
}else if (1 == i) //di
{
close(fd[1]);
dup2(fd[0],STDIN_FILENO);
execlp("wc","wc","-l",NULL);
sys_err("execlp wc error!");
}
return 0;
}
$./brothercommunication
出问题的原因:
图1

管道是需要单向流动。父进程读端和写端没有关闭。
$cat brothercommunication.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<errno.h>
#include<sys/wait.h>
void sys_err(const char *str)
{
perror(str);
exit(1);
}
int main(int argc, char *argv[])
{
int fd[2];
int ret;
int i;
pid_t pid;
ret = pipe(fd);
if(-1 == ret)
{
sys_err("pipe error!");
}
for(i =0;i<2;i++) {
pid = fork();
if(pid == -1)
{
sys_err("fork error!");
}
if(0 == pid)
{
break;
}
}
if(2 == i)
{
close(fd[0]);
close(fd[1]);
wait(NULL);
wait(NULL);
}else if( 0 == i)
{
close(fd[0]);
dup2(fd[1],STDOUT_FILENO);
execlp("ls","ls","-l",NULL);
sys_err("execlp error!");
}else if (1 == i)
{
close(fd[1]);
dup2(fd[0],STDIN_FILENO);
execlp("wc","wc","-l",NULL);
sys_err("execlp wc error!");
}
return 0;
}
$./brothercommunication
4
$ls
brothercommunication brothercommunication.c makefile
$ls|wc -l
3
和实际不一样? 为什么?
实际上是一样的!
命令用错了。
$ls -l |wc -l
4
$ls -l
total 28
-rwxrwxr-x 1 ubuntu ubuntu 20272 1月 16 21:11 brothercommunication
-rw-rw-r-- 1 ubuntu ubuntu 797 1月 16 21:11 brothercommunication.c
-rw-rw-r-- 1 ubuntu ubuntu 169 1月 16 20:48 makefile
本文介绍了一个使用管道进行子进程间通信的示例程序,并详细解释了如何通过创建兄弟进程实现命令链式调用,从ls -l获取输出到使用wc -l计数行数的过程。
4833

被折叠的 条评论
为什么被折叠?



