62 lines
1.1 KiB
C++
62 lines
1.1 KiB
C++
using namespace std;
|
|
#include <iostream>
|
|
#include <stdlib.h>
|
|
#include <sys/types.h>
|
|
#include <unistd.h>
|
|
#include <sys/wait.h>
|
|
|
|
void mult(int x, int y, int id);
|
|
|
|
void sub(int x, int y, int id);
|
|
|
|
void add(int x, int y, int id);
|
|
|
|
int main(int argc, char * argv[])
|
|
{
|
|
int pid;
|
|
cout << "Parent's PID: " << getpid() << endl;
|
|
pid = fork();
|
|
if (pid == 0 ) // child1
|
|
{
|
|
int pidChild2;
|
|
sub(4, 5, getpid());
|
|
|
|
// child1 subtracts numbers
|
|
pidChild2 = fork(); // child2
|
|
if (pidChild2 == 0)
|
|
{
|
|
add(4, 5, getpid());
|
|
exit(0);
|
|
}
|
|
else // child1
|
|
{
|
|
wait(0);
|
|
mult(4, 5, getpid());
|
|
exit(0);
|
|
}
|
|
}
|
|
else // parent of both
|
|
{
|
|
wait(0);
|
|
}
|
|
}
|
|
|
|
void mult(int x, int y, int id)
|
|
{
|
|
cout << "4*5 = " << x*y << endl;
|
|
cout << "Child1's ID: " << id << endl;
|
|
}
|
|
|
|
void sub(int x, int y, int id)
|
|
{
|
|
cout << "4-5 = " << x-y << endl;
|
|
cout << "Child1's ID: " << id << endl;
|
|
}
|
|
|
|
|
|
void add(int x, int y, int id)
|
|
{
|
|
cout << "4+5 = " << x+y << endl;
|
|
cout << "Child2's ID: " << id << endl;
|
|
}
|