Skip to content

Instantly share code, notes, and snippets.

@KangDroid
Created October 19, 2020 00:33
Show Gist options
  • Save KangDroid/0a13691bd6b5ab2e1844a3dbfc3ddb2e to your computer and use it in GitHub Desktop.
Save KangDroid/0a13691bd6b5ab2e1844a3dbfc3ddb2e to your computer and use it in GitHub Desktop.
System Programming Test Practice
#include <iostream>
#include <fstream>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <cstring>
#include <cstdio>
#include <sys/stat.h>
using namespace std;
// Use Standard Library
void create_set() {
unsigned long limit_it = 10000000000;
ofstream file_output("zeros.txt");
for (unsigned long i = 0; i < limit_it; i++) {
if (i % (limit_it / 100) == 0) {
cout << "I: " << i << endl;
}
file_output << 0;
file_output.flush();
if (i == limit_it - 10) {
file_output << 1;
file_output.flush();
}
}
file_output.close();
}
// Use Syscall - Much Faster in TMPFS[RAMDISK] comparing to standard library call
void create_set_syscall() {
unsigned long limit_it = 10000000000;
int fd = open("zeros_syscall.txt", O_RDWR | O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO);
if (fd == -1) {
cout << "File open failed" << endl;
return;
}
dup2(fd, STDOUT_FILENO);
for (unsigned long i = 0; i < limit_it; i++) {
if (i % (limit_it / 100) == 0) {
//cout << "I: " << i << endl;
fflush(stdout);
}
printf("0");
if (i == limit_it - 10) {
printf("1");
fflush(stdout);
}
}
close(fd);
}
int main(int argc, char** argv) {
//create_set_syscall();
if (argc != 2) {
cout << "Usage: file_name process_count" << endl;
return -1;
}
int process_count = atoi(argv[1]);
int fd = open("zeros_syscall.txt", O_RDONLY);
if (fd == -1) {
cout << "Something went wrong with open syscall" << endl;
}
struct stat st;
stat("zeros_syscall.txt", &st);
unsigned long size = st.st_size;
unsigned long buffer_length = size / process_count;
if (size % process_count != 0) {
buffer_length++;
}
char *buffer = new char[buffer_length];
if (buffer == nullptr) {
cout << "Something went wrong" << endl;
}
for (int i = 0; i < process_count; i++) {
pid_t tmp_pid = fork();
if (tmp_pid == 0) {
int read_byte = read(fd, buffer, buffer_length);
if (read_byte == -1) {
exit(255);
}
for (unsigned long a = 0; a < buffer_length; a++) {
if (buffer[a] == '1') {
cout << "Found 1 on " << getpid() << endl;
}
}
exit(1);
}
}
int return_value;
for (int i = 0; i < process_count; i++) {
wait(&return_value);
int tmp_return_value = WEXITSTATUS(return_value);
if (tmp_return_value == 255) {
cout << "Finished unexpectedly" << endl;
cout << tmp_return_value << endl;
} else {
cout << tmp_return_value << endl;
}
}
close(fd);
delete[] buffer;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment