管道(一)
代码实现:
#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<errno.h>
#include<string.h>
#define ERROR_EXIT(m) (perror(m),exit(EXIT_FAILURE))
int main(int argc, char* argv[])
{
//创建数组,放两个文件描述符
int pipefd[2];
if(pipe(pipefd)==-1)
ERROR_EXIT("pipe error");
pid_t pid;
pid=fork();
if(pid==0)
{
close(pipefd[0]);
write(pipefd[1],"hello",5);
close(pipefd[1]);
exit(EXIT_SUCCESS);
}
close(pipefd[1]);
char buf[10]={0};
read(pipefd[0],buf,10);
printf("buf=%s\n",buf);
return 0;
}
实现窗口:
代码示例2:
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<errno.h>
#include<string.h>
#define ERROR_EXIT(m) (perror(m),exit(EXIT_FAILURE))
int main(int argc, char* argv[])
{
//创建数组,放两个文件描述符
int pipefd[2];
if(pipe(pipefd)==-1)
ERROR_EXIT("pipe error");
pid_t pid;
pid=fork();
if(pid==0)
{
dup2(pipefd[1],STDOUT_FILENO);
close(pipefd[1]);
close(pipefd[0]);
execlp("ls","ls",NULL);
fprintf(stderr,"error execute ls\n");
exit(EXIT_SUCCESS);
}
dup2(pipefd[0],STDIN_FILENO);
close(pipefd[0]);
close(pipefd[1]);
execlp("wc","wc","-w",NULL);
fprintf(stderr,"error execute wc\n");
exit(EXIT_SUCCESS);
}
运行窗口: