学习笔记
$ls
makefile mypipe mypipe.c
$ls |wc -l
3
父进程实现ls
子进程实现wc -l
利用wc指令我们可以计算文件的Byte数、字数、或是列数.
dup2
exec
pipe
ls 原来输出到屏幕,现在要把它输出到管道的写端 dup2(fd[1],STDOUT_FILENO);??
dup2不是很熟,需要在学习下!
wc -l 将结果写到屏幕
$wc -l
nihal
dfsdf
sdfsdf
wef
4
可以看出来:$wc -l 命令 从标准输入读取数据
下面的行为无法实现,只能通过隐式回收。
子进程:
close(fd[0]);
父进程:
close(fd[1]);
$cat fatherandsonpipe.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<errno.h>
void sys_err(const char *str)
{
perror(str);
exit(1);
}
int main(int argc, char *argv[])
{
int fd[2];
int ret;
pid_t pid;
ret = pipe(fd);
if(-1 == ret)
{
sys_err("pipe error!");
}
pid = fork();
if(-1 == pid)
{
sys_err("fork error!");
}else if(pid>0)
{
close(fd[0]);//guanbi du duan
dup2(fd[1],STDOUT_FILENO);//STDOUT_FILENO->xie duan
execlp("ls","ls",NULL);
sys_err("exec error!");
}
else if(0 == pid)
{
close(fd[1]);
dup2(fd[0],STDIN_FILENO);
execlp("wc","wc","-l",NULL);
sys_err("wc exec error!");
}
}
$vim fatherandsonpipe.c
$make fatherandsonpipe
gcc fatherandsonpipe.c -o fatherandsonpipe -Wall -g
$./fatherandsonpipe
$4
$ls |wc -l
4
$
程序输出,比较奇怪的原因:
$./fatherandsonpipe
$4
父进程先执行完了,所以bash来抢占终端。
子进程后执行完,所以子进程再输出
如何改变这个现象?
1.父进程sleep 几秒??
$cat fatherandsonpipe.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<errno.h>
void sys_err(const char *str)
{
perror(str);
exit(1);
}
int main(int argc, char *argv[])
{
int fd[2];
int ret;
pid_t pid;
ret = pipe(fd);
if(-1 == ret)
{
sys_err("pipe error!");
}
pid = fork();
if(-1 == pid)
{
sys_err("fork error!");
}else if(pid>0)
{
close(fd[0]);//guanbi du duan
dup2(fd[1],STDOUT_FILENO);//STDOUT_FILENO->xie duan
sleep(1); //父进程睡几秒!
execlp("ls","ls",NULL);
sys_err("exec error!");
}
else if(0 == pid)
{
close(fd[1]);
dup2(fd[0],STDIN_FILENO);
execlp("wc","wc","-l",NULL);
sys_err("wc exec error!");
}
}
$make fatherandsonpipe
gcc fatherandsonpipe.c -o fatherandsonpipe -Wall -g
$./fatherandsonpipe
$4
还是一样。
管道的读写行为:
如果ls 不把数据写进去,子进程处于read阻塞等待。
所以父进程先执行,子进程后执行。
所以sleep是无效的。
所以父进程和子进程的内容互换就可以。
$cat fatherandsonpipe.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<errno.h>
void sys_err(const char *str)
{
perror(str);
exit(1);
}
int main(int argc, char *argv[])
{
int fd[2];
int ret;
pid_t pid;
ret = pipe(fd);
if(-1 == ret)
{
sys_err("pipe error!");
}
pid = fork();
if(-1 == pid)
{
sys_err("fork error!");
}else if(0 == pid)
{
close(fd[0]);//guanbi du duan
dup2(fd[1],STDOUT_FILENO);//STDOUT_FILENO->xie duan
sleep(1);
execlp("ls","ls",NULL);
sys_err("exec error!");
}
else if(0 < pid)
{
close(fd[1]);
dup2(fd[0],STDIN_FILENO);
execlp("wc","wc","-l",NULL);
sys_err("wc exec error!");
}
}
$make fatherandsonpipe
gcc fatherandsonpipe.c -o fatherandsonpipe -Wall -g
$./fatherandsonpip
bash: ./fatherandsonpip: No such file or directory
$./fatherandsonpipe
4
$