popen() 替代方案 [英] popen() alternative

查看:65
本文介绍了popen() 替代方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是这个问题的扩展:popen 创建了一个额外的 sh 进程

My question is extension of this one: popen creates an extra sh process

动机:

1) 我的程序需要创建一个对文件执行 tail 的子项.我需要逐行处理输出.这就是我使用 popen 的原因,因为它返回 FILE *.我可以轻松获取单行,做我需要做的事情并打印出来.

1) My program need to create a child which does tail on a file. I need to process the output line by line. That is why I am using popen because it returns FILE *. I can easily fetch single line, do what I need to do and print it.

popen 的一个问题是你没有得到 child 的 pid(在我的例子中是 tail 命令).

One problem with popen is that you do not get pid of child (tail command in my case).

2) 我的程序不应该在它的子进程完成之前退出.所以我需要做 wait;但是没有pid,我做不到.

2) My program should not exit before its child is done. So I need to do wait; but without pid, I cannot do it.

我怎样才能实现这两个目标?

How can I achieve both the goals?

一个可能的(kludge)解决方案:执行 execvp("tail -f file > tmpfile") 并继续读取该 tmpfile.不过,我不确定这个解决方案有多好.

A possible (kludge) solution: do execvp("tail -f file > tmpfile") and the keep reading that tmpfile. I am not sure how good this solution is, though.

推荐答案

你为什么不使用 pipe/fork/exec 方法?

Why aren't you using pipe/fork/exec method?

pid_t pid = 0;
int pipefd[2];
FILE* output;
char line[256];
int status;

pipe(pipefd); //create a pipe
pid = fork(); //span a child process
if (pid == 0)
{
// Child. Let's redirect its standard output to our pipe and replace process with tail
 close(pipefd[0]);
 dup2(pipefd[1], STDOUT_FILENO);
 dup2(pipefd[1], STDERR_FILENO);
 execl("/usr/bin/tail", "/usr/bin/tail", "-f", "path/to/your/file", (char*) NULL);
}

//Only parent gets here. Listen to what the tail says
close(pipefd[1]);
output = fdopen(pipefd[0], "r");

while(fgets(line, sizeof(line), output)) //listen to what tail writes to its standard output
{
//if you need to kill the tail application, just kill it:
  if(something_goes_wrong)
    kill(pid, SIGKILL);
}

//or wait for the child process to terminate
waitpid(pid, &status, 0);

这篇关于popen() 替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆