首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从PHP调用Linux dup2?

如何从PHP调用Linux dup2?
EN

Stack Overflow用户
提问于 2015-09-01 10:35:06
回答 1查看 489关注 0票数 5

不幸的是,我发现执行外部程序的所有解决方案都不合适,所以我使用了我自己的实现,即pcntl_exec之后的pcntl_fork

但是现在我需要将执行程序的stderr/stdout重定向到某个文件中。很明显,我应该在dup2之后使用某种pcntl_fork Linux调用,但我在PHP中看到的唯一dup2eio_dup2,它看起来不是运行常规流(比如stderr/stdout),而是运行一些异步流。

我如何从PHP调用dup2,或者如何在没有它的情况下重定向std*?

同样的问题(尽管没有细节)没有答案:How do I invoke a dup2() syscall from PHP ?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-09-01 10:58:23

这里有一种不需要dup2的方法。它是基于this answer的。

代码语言:javascript
复制
$pid = pcntl_fork();

switch($pid) {

    case 0:
        // Standard streams (stdin, stdout, stderr) are inherited from
        // parent to child process. We need to close and re-open stdout 
        // before calling pcntl_exec()

        // Close STDOUT
        fclose(STDOUT);

        // Open a new file descriptor. It will be stdout since 
        // stdout has been closed before and 1 is the lowest free
        // file descriptor
        $new_stdout = fopen("test.out", "w");

        // Now exec the child. It's output goes to test.out
        pcntl_exec('/bin/ls');

        // If `pcntl_exec()` succeeds we should not enter this line. However,
        // since we have omitted error checking (see below) it is a good idea
        // to keep the break statement
        break; 

    case -1: 
        echo "error:fork()\n";
        exit(1);

    default:
        echo "Started child $pid\n";
}

为了简洁起见,错误处理被省略了。但是请记住,在系统编程中,应该小心处理任何函数的返回值。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32329436

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档