Skip to content

Instantly share code, notes, and snippets.

@ethercflow
Last active June 11, 2018 10:33
Show Gist options
  • Select an option

  • Save ethercflow/87c0bc3f5873de74756d39f423dc59da to your computer and use it in GitHub Desktop.

Select an option

Save ethercflow/87c0bc3f5873de74756d39f423dc59da to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
i=0
while ((i<20)); do
nohup ./summon-kswapd &
let ++i
echo $i
sleep 1
done
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <pthread.h>
#include <inttypes.h>
#include <assert.h>
#define FILE_SIZE 104857600
#define MAX_VISITOR 4
#define RANGE_SIZE FILE_SIZE / MAX_VISITOR
#define BLOCK_SIZE 4194304
typedef struct {
pthread_t thread;
int task_id;
int fd;
off_t begin;
int range;
} ctx_t;
static int gen_file(char *fname, int size);
static int get_fd(char *fname);
static int destroy_file(char *fname);
void *thread_main(void *arg) {
ctx_t *c = arg;
int n = RANGE_SIZE / BLOCK_SIZE;
char **p = malloc(n * sizeof(char*));
int i;
for (i = 0; i < n; i++) {
p[i] = malloc(BLOCK_SIZE);
memset(p[i], '0', BLOCK_SIZE);
}
i = 0;
assert(lseek(c->fd, c->begin, SEEK_SET) == c->begin);
while (1) {
char *buf = p[i++];
off_t cur = lseek(c->fd, 0, SEEK_CUR);
assert (pread(c->fd, buf, BLOCK_SIZE, cur) == BLOCK_SIZE); // inaccurate
int j = 0;
for (; j < BLOCK_SIZE; j++) {
buf[j] = buf[j] - '2';
}
assert (pwrite(c->fd, buf, BLOCK_SIZE, cur) == BLOCK_SIZE); // inaccurate
lseek(c->fd, cur + BLOCK_SIZE, SEEK_SET);
if (i == n) {
assert(lseek(c->fd, c->begin, SEEK_SET) == c->begin);
i = 0;
}
}
for (i = 0; i < n; i++) {
free(p[i]);
}
return NULL;
}
int main(void) {
char fname[20] = { 0 };
if (gen_file(fname, FILE_SIZE) != 0) {
perror("gen file failed");
}
int fd = get_fd(fname);
if (fd < 0) {
perror("get fd failed");
}
ctx_t *cs = malloc(MAX_VISITOR * sizeof(ctx_t));
int i;
for (i = 0; i < MAX_VISITOR; i++) {
ctx_t *c = &cs[i];
c->task_id = i;
c->fd = fd;
c->begin = BLOCK_SIZE * i;
c->range = BLOCK_SIZE;
pthread_create(&c->thread, NULL, &thread_main, c);
}
for (i = 0; i < MAX_VISITOR; i++) {
ctx_t *c = &cs[i];
pthread_join(c->thread, NULL);
}
if (destroy_file(fname) != 0) {
perror("destroy_file failed, do that by yourself");
}
return 0;
}
static int gen_file(char *fname, int size) {
char cmd[100] = { 0 };
sprintf(fname, "file-%d.txt", getpid());
sprintf(cmd, "base64 /dev/urandom | head -c %d > %s", size, fname);
return system(cmd);
}
static int get_fd(char *fname) {
return open(fname, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
}
static int destroy_file(char *fname) {
char cmd[100] = { 0 };
sprintf(cmd, "rm -rf %s", fname);
return system(cmd);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment