Skip to content

Instantly share code, notes, and snippets.

@libbkmz
Created March 2, 2012 08:33
Show Gist options
  • Save libbkmz/1956781 to your computer and use it in GitHub Desktop.
Save libbkmz/1956781 to your computer and use it in GitHub Desktop.
Lab2
// for getpid, getppid
#include <sys/types.h>
#include <unistd.h>
// for memcpy
#include <string.h>
// for malloc
#include <stdlib.h>
// printf
#include <stdio.h>
// for wait function
#include <sys/wait.h>
#include <iostream>
using namespace std;
int actions();
void act_1();
void act_2();
void act_3();
void act_4();
int act;
char *cmd;
int
main()
{
// cout << " PID: " << getpid() << endl;
// cout << "PPID: " << getppid() << endl;
while(true)
{
act = actions();
switch(act){
case 1:
cout << "Run..." << endl;
act_1();
break;
case 2:
cout << "Executing shell command" << endl;
act_2();
break;
case 3:
cout << "Forking..." << endl;
act_3();
break;
case 4:
cout << "Exiting..." << endl;
act_4();
break;
}
}
}
int
actions()
{
char *line = NULL;
size_t line_len = 0;
cout << "1. Execute enterred command" << endl;
cout << "2. Run 1'st lab" << endl;
cout << "3. Execute fork's alghorithm" << endl;
cout << "4. Exit" << endl;
cout << "Type action: " ;
getline(&line, &line_len, stdin);
return atoi(line);
}
void
act_1()
{
pid_t p;
// forking, and save PPID to p variable
p = fork();
if (p == 0)
{
// critical =) section
cout << "I'm a CHILD" << endl;
cout << "Type command: ";
char *line = NULL;
size_t line_len = 0;
getline(&line, &line_len, stdin);
printf("%s", line);
system(line);
printf("Exiting child!\n");
_exit(0);
}else
{
waitpid(p, 0, 0);
cout << "I'm PARENT" << endl;
}
}
void
act_2()
{
}
void
act_3()
{
}
void
act_4()
{
_exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment