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 << "can't create child " << child_id << " (errno=" << strerror(errno) << ")" << endl; cout << "program aborted"; } void do_parent(int * child, int ind) { int id = waitpid(child[ind-1],NULL,0); cout << "Parent: Child " << ind << " with pid = " << id << " has terminated" << endl; } // actions for child void do_child(int child_id) { cout << "hello. this is child " << child_id << " with pid = " << getpid() << ". sleeping for 10s . .." << endl; sleep(10); cout << "child " << child_id << ": i am back. exit now" << 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