当前位置: 技术问答>linux和unix
如何实现双进程互相保护
来源: 互联网 发布时间:2015-12-24
本文导语: 我需要在进程A中监测进程B是否存在,如果不存在则启动B,而在进程B中要监测进程A是否存在,不存在的话启动A,用过system(),fork()都不行,因为用system启动B时,该system系统调用是阻塞的,必须等到B进程退出后才返回,有谁有什...
我需要在进程A中监测进程B是否存在,如果不存在则启动B,而在进程B中要监测进程A是否存在,不存在的话启动A,用过system(),fork()都不行,因为用system启动B时,该system系统调用是阻塞的,必须等到B进程退出后才返回,有谁有什么好的意见.谢谢!
|
You can use two PIPEs to implement this, it is easier. one disadvantage is that you need an additional thread to start the other process if it ends. you can look at ProcA as ThreadA in process A, and ProcB as ThreadB is in process B in the following description:
1) ProcA open two pipes, pipeA[2], pipeB[2]
2) ProcA starts ProcB
3) ProcA closes pipeA[1] and pipeB[0], and ProcB closes pipeA[0] and pipeB[1]
4) ProcA reads pipeA[0], and ProcB reads pipeB[0]. with read(pipeA[0], buf, num);
5) ProcA and ProcB will be blocked, actually the threads will be blocked, because no data is in the pipe. if the read() returns, that means the process at the other end of the pipe ends. then the thread nees to restart the process. before this, close all file descriptors related to the pipeA/pipeB and then start from step 1.
i think this implementation is very simple, and sovle the problem of detecting whether the process exists or not.
please refer to the figure 4.21 in "UNIX network programming Volume 2" for the details on how to handle PIPE and FIFO.
Regards
1) ProcA open two pipes, pipeA[2], pipeB[2]
2) ProcA starts ProcB
3) ProcA closes pipeA[1] and pipeB[0], and ProcB closes pipeA[0] and pipeB[1]
4) ProcA reads pipeA[0], and ProcB reads pipeB[0]. with read(pipeA[0], buf, num);
5) ProcA and ProcB will be blocked, actually the threads will be blocked, because no data is in the pipe. if the read() returns, that means the process at the other end of the pipe ends. then the thread nees to restart the process. before this, close all file descriptors related to the pipeA/pipeB and then start from step 1.
i think this implementation is very simple, and sovle the problem of detecting whether the process exists or not.
please refer to the figure 4.21 in "UNIX network programming Volume 2" for the details on how to handle PIPE and FIFO.
Regards
|
在单独的子进程中处理system
|
用vfork + exec试试