By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,193 Members | 826 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,193 IT Pros & Developers. It's quick & easy.


P: 2
i need to write a (c,c++) program that has a parent and child process. The parent process forks the child, then calls a function which prints out the parent and child process id (with a tag indicating which pid is which). The parent then waits for the child to complete.
Once forked, the child calls a function which sleeps for a period of seconds where the sleep time in seconds is (command line) input as a startup parameter to the program (data sharing between parent and child). Once the child wakes up, it prints out the date (do not use system to do the date, but find the underlying OS system call) and terminates. The printout should delineate between parent and child.
Nov 1 '06 #1
Share this Question
Share on Google+
2 Replies

Expert 100+
P: 1,510
do you know how fork() works? i.e.
UNIX creates a new process with the fork system call
pid = fork();

Unix makes a clone (identical copy) of the processes
After the fork both processes execute in parallel
Original process is the parent and pid is non zero, i.e. the PID of the child
New process is the child and pid is zero.
Both processes separate, i.e. have separate copies of global and local data, etc.
The child and parent then execute in parallel; obviously if there is only one processor they are time-shared.
Open files are shared between parent and child. Initially, the child will have a copy of the parents memory, but it will be a separate copy (at least until parent or child modify it).
Heavyweight processes, i.e. called heavyweight because that have speperate stacks, heap, etc.

a simple program looks like
Expand|Select|Wrap|Line Numbers
  1.    #include <iostream.h>
  2.     #include <unistd.h>
  3.     int main(void)
  4.     {
  5.             int pid;
  6.             if((pid = fork()) < 0) // create new process
  7.                 cout << "Fork failed" << endl;
  8.             else
  9.                 if (pid == 0) cout << "The child" << endl;
  10.                 else          cout << "The parent, child pid " << pid << endl;
  11.             return 0;
  12.     }
Nov 1 '06 #2

P: 1
yes..about that.. if i want n children to be created. each of them reading a command from an array .. i mean something like this
a[i] - will contain the i-th command which i want to execute
pid_t pid;
for (i=0;i<n;i++)
if (pid==0) // the parent
else execlp( a[i],a[i],"","",NULL);
Is this ok? I mean.. it will generate n procceses each of them executing their command ? .. the execlp function is a bit confusing as well...
Feb 2 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.