PHP派生意外行为:父进程等待,直到子进程退出 [英] PHP fork unexpected behaviour: Parent process waits till the child process exits

查看:69
本文介绍了PHP派生意外行为:父进程等待,直到子进程退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个php脚本,可以向用户显示Web表单.当用户提交表单时,我将数据保存在数据库中,然后派生一个进程,儿子,向受新更改影响的数据库用户发送一些SMS.

I have a php script that displays a web form to the user. When the user submits the form, i save the data in the database and then i fork a process, the son, to send some SMS to the database users afected with the new changes.

当我分叉时,我会检查儿子,然后儿子正确发送SMS,最后退出.但是由于某种原因,父亲等待儿子去完成任务.我不知道为什么会这样..

When i fork, i check for the son, and he sends the SMS correctly, and in the end exits. But by some reason, the father waits for the son to do his tasks. I dunno why this is happening..

以下是我的代码示例:

    // before this point, i've inserted some data in the database, and now i commit the transaction
    $conn->commit();
    $pid = pcntl_fork();
if ($pid == 0) {    // its the son, so he will send the messages
  $conn = new PDO('oci:dbname='.SERVER.';charset='.CHARSET, DATABASE, PASSWORD);
  $suppliersPhoneNumber = getSuppliersPhoneNumber($conn, ...);
  $conn = null;
  $sms = new MessageSender($suppliersPhoneNumber, $_POST['subCategory']);
  $sms->handleMessages();   // send the sms     
      //sleep(60);      
  exit(0);  // the son won't execute more code
}/

代码为"sleep(60)"的行是我如何知道父亲在等待孩子的信息.但是,如果儿子离开,这怎么可能呢?我知道父亲在等儿子,实际上是因为我的脚本冻结了1分钟,即等待时间.

The line with the code "sleep(60)" is how i know that the father is waiting for the child. But how is this possible if the son exits?? I know the father waits for the son, cause in fact my script freezes for 1 minute, the waiting time.

我的想法是让一个父亲在数据库中插入所需的数据,最后他产生了一个新的孩子来发送消息,但是他没有等待他,因此我们可以向用户发送响应页面,说一切正常,同时有效地发送了消息.

My idea is to have a father inserting the required data in the database, in the end he spawns a new child to send the messages, but doesn't waits for him, so we can send a response page to the user saying everything went fine, while the messages are effectively being sent.

这是怎么回事?

提前考虑

编辑问题没有解决,而是我遵循了下面注册的Paulo H.的解决方案.确实,这是一种更好的方法.

EDIT The problem was not solve, instead i followed the solution of Paulo H. registed below. Indeed it was a better way.

推荐答案

我相信您正在使用Apache运行此代码,建议您运行完全

I believe that you are using Apache to run this code, I suggest you run a completely separate process in the background.

我认为问题正在发生,因为Apache在将信息发送到浏览器之前等待该子进程.无论如何,如果不在php-cli脚本中,不建议使用fork.

I think the problem is happening because Apache waits for this child process before sending the information to the browser. Anyway do not recommend fork if not in a php-cli script.

通常,子进程一直处于僵尸模式,直到父进程调用"

Usually the child process stay in zombie mode until the parent process call a "wait", but there not seems to be the case.

这篇关于PHP派生意外行为:父进程等待,直到子进程退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆