popen()完成替代 [英] popen() alternative
问题描述
我的问题是一个延伸:的popen创建一个额外的sh进程
My question is extension of this one: popen creates an extra sh process
动机:
1)我的程序需要创建一个孩子做哪些<$ C $ C>尾上的文件。我需要处理由线路输出线。这就是为什么我使用的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这一个问题是,你不(在我的情况tail命令)获得孩子的PID。
One problem with popen is that you do not get pid of child (tail command in my case).
2)我的计划应其子之前不会退出完成。所以,我需要做的等
;但没有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?
一个可能的(组装机)的解决方案:做execvp(尾-f文件> 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.
推荐答案
你为什么不使用管/叉/ 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屋!