php接收dup,如何从PHP调用Linux dup2?

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

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

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

解决方法:

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

$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";

}

为简洁起见,省略了错误处理.但请记住,在系统编程中应该仔细处理任何函数返回值.

标签:php,linux

来源: https://codeday.me/bug/20190623/1272572.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值