popen()替代方案

har*_*ari 10 c process exec popen

我的问题是这个问题的延伸:popen创造了一个额外的过程

动机:

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

popen的一个问题是你没有得到孩子的pid(在我的情况下是tail命令).

2)我的程序不应该在孩子完成之前退出.所以我需要做wait; 但没有pid,我不能这样做.

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

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

Pat*_*ryk 16

你为什么不使用pipe/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);
Run Code Online (Sandbox Code Playgroud)