一、利用管道获取子进程的输出
#include <stdio.h>
int main()
{
int ret;
char buf[1024];
FILE* pp = popen("ls", "r");
if (!pp)
{
fprintf(stderr, "popen error!/n");
return 0;
}
while ( (ret = fread(buf, 1, 1023, pp)) > 0)
{
buf[ret] = 0;
fprintf(stdout, "%s", buf);
}
fprintf(stdout, "/n");
pclose(pp);
return 0;
}
二、利用管道向子进程的输入数据
没有想到好的命令,自己写了如下一个test程序,该程序从stdin读取数据写入到一个文件
//test.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char* line;
char buf[1024];
FILE* fp = fopen("test.txt", "w");
if (!fp)
{
exit(-1);
}
while (line = fgets(buf, 1024, stdin))
{
fwrite(line, 1, strlen(line), fp);
fflush(fp);
}
return 0;
}
然后使用如下程序测试管道
//po.c
#include <stdio.h>
#include <string.h>
int main()
{
int ret;
char buf[1024];
char* ptr;
FILE* pp = popen("./test", "w");
if (!pp)
{
fprintf(stderr, "popen error!/n");
return 0;
}
ptr = "test line 1/n";
fwrite(ptr, 1, strlen(ptr), pp);
ptr = "test line 2/n";
fwrite(ptr, 1, strlen(ptr), pp);
pclose(pp);
return 0;
}
编译test.c
gcc -o test test.c
得到可执行文件test
编译po.c
gcc -o po po.c
得到可执行文件po
运行
./po
得到test.txt文件
cat test.txt
内容如下:
test line 1
test line 2
双向管道的使用代码,源自man pipe
#include <sys/wait.h>
#include <assert.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;
assert(argc == 2);
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]));
close(pipefd[1]); /* Reader will see EOF */
wait(NULL); /* Wait for child */
exit(EXIT_SUCCESS);
}
}
linux管道编程
最新推荐文章于 2024-09-03 23:46:06 发布