父子进程发送和接收消息

来源:互联网 发布:激光脱毛 知乎 编辑:程序博客网 时间:2024/06/16 21:22

用newlisp cilk API可以实现多进程通信。在实际应用中,父进程发送消息给多个子进程,使得父进程可以专注于自己的工作,把一些额外的工作交给子进程去完成,做到对父进程任务无阻塞的效果。

这里的例子程序是process.lsp文件,这样调用:

./process.lsp --process-number=5child-process-list: (4289 4288 4287 4286 4285)child process: 4289child process: 4288child process: 4287child process: 4286child process: 4285

输入5,告知需要创建5个子进程。

5个子进程被创建的信息被父进程打印在控制台上。

5个子进程都有自己的日志文件,里面是接收到来自父进程的消息。

  -rw-r--r-- 1 dean dean    9 Sep 13 19:29 4285.log  -rw-r--r-- 1 dean dean    9 Sep 13 19:29 4286.log  -rw-r--r-- 1 dean dean    9 Sep 13 19:29 4287.log  -rw-r--r-- 1 dean dean    9 Sep 13 19:29 4288.log  -rw-r--r-- 1 dean dean    9 Sep 13 19:29 4289.log
消息内容如下:

$ cat 4285.log test msg

现在看下实现代码:

首先有一个args.lsp负责解析参数

;; parse args into Tree(define (parse-args)  (new Tree 'ArgsTree)  (dolist (arg (main-args))    (if (find "=" arg)(begin  (setq pair (parse arg "="))  (ArgsTree (pair 0) (pair 1))  ))    )  )

然后有一个process.lsp完成所有工作

#!/usr/bin/newlisp(load "args.lsp")(parse-args)(setq process-number (int (ArgsTree "--process-number")))(define (child-process)  (setq ppid (sys-info 6)) ; get parent pid  (setq cur-pid (sys-info 7))  (while true    (if (receive ppid msg)   (begin     ;; get new message from queue     (append-file (string cur-pid ".log") (string msg "\n"))     )   (begin     ;; get nothing from queue, sleep 1 second     (sleep 1000)     )   )    )  ); parent starts child processes(dotimes (i process-number)  (spawn 'result (child-process) true)  );; parent send one msg to each child process(setf child-process-list (sync))(println "child-process-list: " child-process-list)(dolist (cpid child-process-list)  (println "child process: " cpid)  (send cpid "test msg")  );; quit in at most 10 seconds(sync 10000)(abort)(exit)

说明

1. 父子进程消息交换

父进程通过send发送消息,子进程通过receiv接收消息,使用了循环和等待,一直反复接收消息。

2. spawn执行后,'result不会立刻得到结果,值为nil。这不是错误,是newlisp这么设计的。需要等到(sync)调用后才能获得子进程返回的结果。

Launches the evaluation of exp as a child process and immediately returns. The symbol in sym is quoted and receives the result of the evaluation when the function sync is executed. 

3. (sync 10000)比(sleep 10000)好,如果子进程及时在10000毫秒内退出,sync会立刻结束。

When int-timeout in milliseconds is specified, sync waits for child processes launched with spawn to finish. Whenever a child process finishes, sync assigns the evaluation result of the spawned subtask to the symbol specified in the spawn statement. The sync returns true if all child processes have been processed or nil if the timeout value has been reached and more child processes are pending.


4. (sync) 无参数的sync函数作用完全不同,返回子进程ID list,用于进程间通信。

Without any parameter, sync returns a list of pending child process PIDs (process identifiers), for which results have not been processed yet.

5. (abort)不能少,否则会出现子进程没有及时关闭的情况

0 0
原创粉丝点击