我的问题是这个问题的扩展:popen creates an extra sh process
动机:
1)我的程序需要创建一个在文件上执行tail的子级。我需要逐行处理输出。这就是我使用popen的原因,因为它返回FILE *。我可以很容易地获取单行,做我需要做的事情并打印它。
popen的一个问题是你没有得到孩子的pid (在我的例子中是尾部命令)。
2)我的程序不应该在它的子程序完成之前退出。所以我需要做wait;但是如果没有pid,我就做不到。
我如何才能同时实现这两个目标?
一种可能的解决方案:执行execvp("tail -f file > tmpfile")并继续读取该tmpfile。不过,我不确定这个解决方案有多好。
发布于 2011-07-19 16:23:58
为什么不使用管道/fork/exec方法?
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);发布于 2011-07-19 16:13:06
pipe,它是exec*系列和fdopen的一个函数。这是非标准的,但popen.wait。只需将管道读到EOF.execvp("tail -f file > tmpfile")将不起作用,重定向是shell的一个功能,并且您没有在这里运行shell。即使它起作用了,这也是一个糟糕的解决方案。假设您已经读到了文件的末尾,但是子进程还没有结束。你是做什么的?发布于 2011-07-19 15:44:52
您可以使用wait,因为它不需要PID等待,而只是等待Any子进程退出。如果您已经创建了其他子进程,则可以跟踪它们,如果wait返回未知PID,则可以假定它来自您的popen进程。
https://stackoverflow.com/questions/6743771
复制相似问题