Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <unistd.h>
- #include <err.h>
- #include <time.h>
- #include <fcntl.h>
- #include <stdbool.h>
- #include <stdlib.h>
- #include <errno.h>
- #include <sys/wait.h>
- #include <string.h>
- int getCode(int);
- bool isCondition(time_t, time_t, int, int);
- int writeToFile(int, time_t, time_t, int);
- int convert(char*);
- int getCode(int status) {
- if (WIFEXITED(status)) {
- return WEXITSTATUS(status);
- }
- return 129;
- }
- bool isCondition(time_t start, time_t end, int code, int limit) {
- return code != 0 && limit < (end - start);
- }
- int writeToFile(int fd, time_t start, time_t end, int exitCode) {
- return dprintf(fd, "%ld %ld %d\n", start, end, exitCode);
- }
- int convert(char* str) {
- if (strlen(str) != 1 || str[0] < '1' || str[1] > '9') {
- errx(5, "invalid number");
- }
- return str[0] - '0';
- }
- int main(int argc, char* argv[]) {
- //argv -> P secs Q args
- if (argc < 3) {
- errx(1, "Invalid number of arguments");
- }
- int limit = convert(argv[1]);
- int conditionInRow = 0;
- int fd = open("run.log", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
- if (-1 == fd) {
- err(4, "error opening/creating file");
- }
- while(conditionInRow != 2) {
- pid_t pid = fork();
- if(-1 == pid) {
- err(2, "error forking");
- }
- if (0 == pid) {
- execvp(argv[2], argv + 2);
- err(3, "error executing");
- }
- time_t start = time(NULL);
- int status;
- wait(&status);
- time_t end = time(NULL);
- int code = getCode(status);
- if (writeToFile(fd, start, end, code) < 0) {
- err(4, "error writing to fd");
- }
- if (isCondition(start, end, code, limit)) {
- conditionInRow++;
- } else {
- conditionInRow = 0;
- }
- }
- close(fd);
- }
Advertisement
Add Comment
Please, Sign In to add comment