Threads and Scheduling
at main 81 lines 2.1 kB view raw
1#include <assert.h> 2#include <stdio.h> 3#include <string.h> 4#include <time.h> 5#include <unistd.h> 6#include "lib/enchufe.h" 7#include "lib/lib.h" 8#include "lib/log.h" 9#define BUF_LEN 0x100 10#define SLEEP_TIME 3 11size_t total_time = 0; 12 13int main(int argc, char** argv) { 14 assert(argc == 3 && "You must provide three arguments."); 15 16 // Create the socket 17 IPv4 ip = parse_address(argv[1]); 18 Port port = (Port)atoi(argv[2]); 19 log(INFO, "Connecting to: %d.%d.%d.%d on port: %d\n", ip.bytes[0], ip.bytes[1], ip.bytes[2], ip.bytes[3], port); 20 21 Enchufe enchufe = enchufa(ip, port); 22 conecta(enchufe); 23 24 /* run the command 25 * here I used `ps auxww -Aeo args` in order to use the entire string used 26 * by `ps`. 27 */ 28 FILE* fp = popen("ps -o args | sed '1d'", "r"); 29 exists(fp); 30 31 // Initialize random seed generator. 32 srand((uint32_t)time(NULL)); 33 34 char program[BUF_LEN]; 35 while (fgets(program, BUF_LEN, fp)) { 36 // path has a line feed character at the end that must be removed 37 size_t len = safe_strlen(program, BUF_LEN) - 1; 38 program[len] = '\0'; 39 40 // Create the process that will be sent 41 Proc proc = { 42 .time = (Time)rand() % SLEEP_TIME, 43 .program = { 44 .buf = (Byte*)program, 45 .len = len, 46 }, 47 }; 48 total_time += proc.time; 49 50 // Send the process. 51 log(INFO, "Sent program: %s with time %d.\n", proc.program.buf, proc.time); 52 Buffer in_buf = serialize(proc); 53 zumba(enchufe, in_buf); 54 55 /* Clear the buffer for the program and free the memory associated to 56 * what was just sent. 57 */ 58 memset(program, 0, BUF_LEN); 59 free(in_buf.buf); 60 61 // Create new buffer to receive output from cluster. 62 Byte buf[BUF_LEN] = {0}; 63 Buffer out_buf = { 64 .buf = buf, 65 .len = BUF_LEN, 66 }; 67 // Receive message from cluster. 68 size_t msg_len = recibe(enchufe, out_buf); 69 assert(safe_strlen((char*)out_buf.buf, BUF_LEN) == msg_len); 70 log(INFO, "Received: %s.\n", (char*)out_buf.buf); 71 } 72 73 // Let the user know that the program is done. 74 log(INFO, "Done.\n"); 75 log(INFO, "Total time: %zu.\n", total_time); 76 77 // Close socket. 78 desenchufa(enchufe); 79 80 return 0; 81}