lab2-ex

lab2-ex - return 0; } // print out the error message void...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
#include <iostream> #include <unistd.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> # using namespace std; u void show_error(int); void do_parent(int *, int); void do_child(int); v int main() { // store the return value of fork pid_t pid; int child[4]; cout << "hello. this is parent" << endl; for (int i=1; i<=4; i++) { pid=fork(); if (pid<0) { // this block is entered if can't create child show_error(i); exit(-1); } else if (pid==0) { // this block is entered by child only do_child(i); // quit the process explicitly exit(0); } else { child[i-1]=pid; } } for (int i=4; i>0; i--) { do_parent(child, i); } cout << "end of parent" << endl;
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: return 0; } // print out the error message void show_error(int child_id) { cout &lt;&lt; &quot;can't create child &quot; &lt;&lt; child_id &lt;&lt; &quot; (errno=&quot; &lt;&lt; strerror(errno) &lt;&lt; &quot;)&quot; &lt;&lt; endl; cout &lt;&lt; &quot;program aborted&quot;; } void do_parent(int * child, int ind) { int id = waitpid(child[ind-1],NULL,0); cout &lt;&lt; &quot;Parent: Child &quot; &lt;&lt; ind &lt;&lt; &quot; with pid = &quot; &lt;&lt; id &lt;&lt; &quot; has terminated&quot; &lt;&lt; endl; } // actions for child void do_child(int child_id) { cout &lt;&lt; &quot;hello. this is child &quot; &lt;&lt; child_id &lt;&lt; &quot; with pid = &quot; &lt;&lt; getpid() &lt;&lt; &quot;. sleeping for 10s . ..&quot; &lt;&lt; endl; sleep(10); cout &lt;&lt; &quot;child &quot; &lt;&lt; child_id &lt;&lt; &quot;: i am back. exit now&quot; &lt;&lt; endl; }...
View Full Document

Page1 / 2

lab2-ex - return 0; } // print out the error message void...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online