使用pipe实现一个简单的类似tee命令的功能
/*
testPipe.c
*/
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{
int pipefd[2];
pid_t cpid;
char buf;
FILE *fp = NULL;
char file_name[256];
if ((argc != 2) && (argc != 3)) {
fprintf(stderr, "Usage: %s <string> [write2file]\n", argv[0]);
exit(EXIT_FAILURE);
}
memset(file_name,'\0',256);
if(argc == 3)
strncpy(file_name,argv[2],strlen(argv[2]));
else
strncpy(file_name,"testPipe",strlen("testPipe"));
fp = fopen(file_name,"w+");
if(fp == NULL)
{
printf("open file error\n");
return -1;
}
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
cpid = fork();
if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (cpid == 0) { /* Child reads from pipe */
close(pipefd[1]); /* Close unused write end */
while (read(pipefd[0], &buf, 1) > 0)
{
write(STDOUT_FILENO, &buf, 1);
}
write(STDOUT_FILENO, "\n", 1);
close(pipefd[0]);
_exit(EXIT_SUCCESS);
} else { /* Parent writes argv[1] to pipe */
close(pipefd[0]); /* Close unused read end */
write(pipefd[1], argv[1], strlen(argv[1]));
printf("str:%s,len:%d\n",argv[1],strlen(argv[1]));
fwrite(argv[1],1,strlen(argv[1]),fp);
close(pipefd[1]); /* Reader will see EOF */
fclose(fp);
wait(NULL); /* Wait for child */
exit(EXIT_SUCCESS);
}
}