DUtils

Doemes Utilities - Various Programs I frequently use
git clone git://xatko.vsos.ethz.ch/DUtils.git
Log | Files | Refs

commit 70bd27857accf796639ab010885620e6bbd63163
Author: Dominik Schmidt <das1993@hotmail.com>
Date:   Mon, 16 Jul 2018 16:05:55 +0000

Initial commit

Add the makefile, bytehist which counts how many timesa certain byte
value occurs, and execpipe, which pipes together multiple commands

Diffstat:
Makefile | 25+++++++++++++++++++++++++
bytehist.c | 35+++++++++++++++++++++++++++++++++++
execpipe.c | 46++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 106 insertions(+), 0 deletions(-)

diff --git a/Makefile b/Makefile @@ -0,0 +1,25 @@ +CC ?= cc +CFLAGS ?= -g +DESTDIR ?= ~/.local +BINDIR ?= $(DESTDIR)/bin +MANDIR ?= $(DESTDIR)/share/man/ + +PROGS=bytehist execpipe + +all: $(PROGS) + +%:%.c + $(CC) $(CFLAGS) $^ -o $@ + +$(BINDIR)/%: % + install -m 0755 $< $@ + +$(MANDIR)/man1/%: % + install -m 0755 $< $@ + +.PHONY:install clean + +install: $(addprefix $(INSTALLDIR)/,$(PROGS)) + +clean: + rm -f $(PROGS) diff --git a/bytehist.c b/bytehist.c @@ -0,0 +1,35 @@ +#include <stdio.h> +#include <unistd.h> +#include <stdint.h> +#include <string.h> + +int main(int argc, char **argv){ + unsigned char buf[4092]; + size_t hist[256]; + size_t ret=0; + size_t i; + size_t cnt=0; + int relative=1; + if(argc>1){ + if(strcmp("-r", argv[1]) == 0){ + relative=0; + } + } + for(i=0; i<255; i++){ + hist[i]=0; + } + while((ret=read(STDIN_FILENO, buf, sizeof(buf)))>0){ + for(i=0; i<ret; i++){ + hist[(size_t)(buf[i])]++; + } + cnt+=ret; + } + for(i=0; i<256; i++){ + if(relative){ + printf("%lu\t%lu\n", i, hist[i]); + } + else{ + printf("%lu\t%e\n", i, (double)hist[i]/cnt); + } + } +} diff --git a/execpipe.c b/execpipe.c @@ -0,0 +1,46 @@ +#include <unistd.h> +#include <stdio.h> +#include <sys/types.h> +#include <stdlib.h> + +int process(int argc, char **argv); + +void do_shell(char *cmd){ + execl("/bin/sh", "sh", "-c", cmd, (char *) 0); +} + +void split(int argc, char **argv){ + int pipefd[2]; + if(pipe(pipefd)==-1){ + perror("Pipeline failed"); + exit(EXIT_FAILURE); + } + pid_t pid=fork(); + if(pid==-1){ + perror("Forking failed"); + exit(EXIT_FAILURE); + } + else if(pid==0){ + dup2(pipefd[0],STDIN_FILENO); + close(pipefd[1]); + process(argc-1,argv+1); + } + else{ + dup2(pipefd[1],STDOUT_FILENO); + close(pipefd[0]); + do_shell(argv[0]); + } +} + +int process(int argc, char **argv){ + if(argc==1){ + do_shell(argv[0]); + } + else if(argc>1){ + split(argc,argv); + } +} + +int main(int argc, char **argv){ + process(argc-1,argv+1); +}