ubuntu - pcntl 子進(jìn)程引用并修改父進(jìn)程數(shù)據(jù)的問題??
問題描述
代碼:
$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é)果:

進(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)文章:
1. javascript - immutable配合react提升性能?2. javascript - sublime快鍵鍵問題3. 如何解決Centos下Docker服務(wù)啟動(dòng)無響應(yīng),且輸入docker命令無響應(yīng)?4. css - 寫頁面遇到個(gè)布局問題,求大佬們幫解答,在線等,急!~5. phpstudy8.1支持win11系統(tǒng)嗎?6. javascript - 移動(dòng)端上不能實(shí)現(xiàn)拖拽布局嗎?7. 實(shí)現(xiàn)bing搜索工具urlAPI提交8. vue.js - Vue 如何像Angular.js watch 一樣監(jiān)聽數(shù)據(jù)變化9. javascript - nodejs關(guān)于進(jìn)程間發(fā)送句柄的一點(diǎn)疑問10. index.php錯(cuò)誤,求指點(diǎn)

網(wǎng)公網(wǎng)安備