Yearly Archives: 2016
Tail logs with color for Monolog 1
#1. Copy/paste the below lines in your .bashrc
tailf-with-colors () {
if [ -z "$1" ] ; then
echo "Please specify a file for monitoring"
return
fi
tail -f $1 | awk '
{matched=0}
/INFO:/ {matched=1; print "\033[0;37m" $0 "\033[0m"} # WHITE
/NOTICE:/ {matched=1; print "\033[0;36m" $0 "\033[0m"} # CYAN
/WARNING:/ {matched=1; print "\033[0;34m" $0 "\033[0m"} # BLUE
/ERROR:/ {matched=1; print "\033[0;31m" $0 "\033[0m"} # RED
/ALERT:/ {matched=1; print "\033[0;35m" $0 "\033[0m"} # PURPLE
matched==0 {print "\033[0;33m" $0 "\033[0m"} # YELLOW
'
}
#2. Run source ~/.bashrc -- to reload
#3. Run tailf-with-colors <filename>
C/C++: Pass random value from parent to child after fork() via a pipe()
The following code will create a pipe for each child, fork the process as many times as it is needed and send from the parent to each child a random int value, finally the children will read the value and terminate.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
int main(int argc, char *argv[]) {
int count = 3;
int fd[count][2];
int pid[count];
srand(time(NULL));
// create pipe descriptors
for (int i = 0; i < count; i++) {
pipe(fd[i]);
// fork() returns 0 for child process, child-pid for parent process.
pid[i] = fork();
if (pid[i] != 0) {
// parent: writing only, so close read-descriptor.
close(fd[i][0]);
// send the value on the write-descriptor.
int r = rand();
write(fd[i][1], &r, sizeof(r));
printf("Parent(%d) send value: %d\n", getpid(), r);
// close the write descriptor
close(fd[i][1]);
} else {
// child: reading only, so close the write-descriptor
close(fd[i][1]);
// now read the data (will block)
int id;
read(fd[i][0], &id, sizeof(id));
printf("%d Child(%d) received value: %d\n", i, getpid(), id);
// close the read-descriptor
close(fd[i][0]);
//TODO cleanup fd that are not needed
break;
}
}
return 0;
}
C/C++: Pass value from parent to child after fork() via a pipe()
The following code will create a pipe, fork the process and then send from the parent to the child an int value (the id we want to give to the child), finally the child will read the value and terminate.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int fd[2];
int childID = 0;
// create pipe descriptors
pipe(fd);
// fork() returns 0 for child process, child-pid for parent process.
if (fork() != 0) {
// parent: writing only, so close read-descriptor.
close(fd[0]);
// send the childID on the write-descriptor.
childID = 1;
write(fd[1], &childID, sizeof(childID));
printf("Parent(%d) send childID: %d\n", getpid(), childID);
// close the write descriptor
close(fd[1]);
} else {
// child: reading only, so close the write-descriptor
close(fd[1]);
// now read the data (will block until it succeeds)
read(fd[0], &childID, sizeof(childID));
printf("Child(%d) received childID: %d\n", getpid(), childID);
// close the read-descriptor
close(fd[0]);
}
return 0;
}



