成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

ubuntu - pcntl 子進(jìn)程引用并修改父進(jìn)程數(shù)據(jù)的問題??

瀏覽:137日期:2024-07-07 15:51:59

問題描述

代碼:

$data = array();$p = pcntl_fork();if ($p === -1) { exit(’創(chuàng)建進(jìn)程失敗!’ . PHP_EOL);} else if ($p === 0) { // 修改主進(jìn)程中的數(shù)據(jù) $data = array(’cxl’ , ’ys’);} else { pcntl_wait($status);// 子進(jìn)程返回后,查看數(shù)據(jù)變動(dòng) print_r($data); // 結(jié)果 array(),沒有發(fā)生任何變化! // 子進(jìn)程無法修改主進(jìn)程中的數(shù)據(jù)。 // 子進(jìn)程中該如何修改主進(jìn)程中的數(shù)據(jù),實(shí)現(xiàn)數(shù)據(jù)共享??}

結(jié)果:

ubuntu - pcntl 子進(jìn)程引用并修改父進(jìn)程數(shù)據(jù)的問題??

進(jìn)程間該如何進(jìn)行數(shù)據(jù)交流??

問題解答

回答1:

子進(jìn)程創(chuàng)建后,已經(jīng)與父進(jìn)程的變量數(shù)據(jù)脫鉤,如果要實(shí)現(xiàn)子進(jìn)程修改父進(jìn)程變量,需要通過進(jìn)程間通訊并自行實(shí)現(xiàn)相關(guān)代碼來完成。當(dāng)然,也可以通過共享內(nèi)存的方式實(shí)現(xiàn)變量的共享。

回答2:

進(jìn)程間通信可用的方法多了去了。最常見的,TCP。

回答3:

剛好在學(xué)習(xí)pcntl,也想到進(jìn)程間通信的事情,搜到的其中一個(gè)可用方法-使用消息隊(duì)列,覺得不太復(fù)雜,于是在你代碼上加了幾句,可以試試,互助共勉。

// 創(chuàng)建key和消息隊(duì)列$msg_key = ftok(__FILE__, ’a’);$msg_queue = msg_get_queue($msg_key);$data = array();$p = pcntl_fork();if ($p === -1) { exit(’創(chuàng)建進(jìn)程失敗!’ . PHP_EOL);} else if ($p === 0) { // 修改主進(jìn)程中的數(shù)據(jù) // 將修改的數(shù)據(jù)發(fā)送到消息隊(duì)列 msg_send($msg_queue, 1, array(’cxl’ , ’ys’)); exit();} else { pcntl_wait($status);// 子進(jìn)程返回后,查看數(shù)據(jù)變動(dòng) // 接收隊(duì)列中的數(shù)據(jù) msg_receive($msg_queue, 1, $msg_type, 1024, $msg); // 銷毀隊(duì)列 msg_remove_queue($msg_queue);$data = $msg; print_r($data); }

相關(guān)文章: