jeudi 24 février 2011

Get the username and home directory in a C program

Don't use getlogin or cuserid functions.
Don't try to guess the home directory from the username (/home/username is not working all the time).

Use getpwuid instead:

#include <sys/types.h>
#include <pwd.h>
[...]
char* username = getpwuid(getuid())->pw_name;
char* homedir = getpwuid(getuid())->pw_dir;

This works all the time, in particular if the process is not controlled by a terminal.

Stdio buffering

Nice article about stdio buffering:

http://www.pixelbeat.org/programming/stdio_buffering/

I recently had the following problem: I launch p1 | p2 (piped processes, p2 is the receiver), and p2 isn't receiving on its stdin the data (a few bytes) p1 is writing to its stdout. After a while I discovered that the data is buffered (4096 bytes if the process output is not redirected to a terminal, else it is line buffered).

To make it line-buffered all the time, use setlinebuf:

#include <stdio.h>
[...]
setlinebuf(stdout);

Since there is no setlinebuf in windows, a portable manner to do this is:

#include <stdio.h>
[...]
printf(line);
fflush(stdout); //to do after each printed line

vendredi 4 février 2011

How to automout, autocopy and autoeject discs

Tested in Ubuntu 10.10.

sudo apt-get install ddrescue

create a file named 'autocopy' with following content:

#!/bin/bash

CDDEV="/dev/sr0"
TARGET_DIR="/saved"

IFS=$'\n'

while [ 1 ]
do
input="$(cat /etc/mtab | grep $CDDEV | awk 'END { print $2 }' | sed 's/\\040/ /g')"
if [ -d "$input" ]
then
cd $input
for file in *
do
if [ -d $file ]
then
cd $file
for file in *
do
echo copying: $file
time ddrescue $file $TARGET_DIR/$file
done
cd ..
else
echo copying: $file
time ddrescue $file $TARGET_DIR/$file
fi
done
cd ..
umount -l $CDDEV
while ! eject $CDDEV
do
sleep 1
done
fi
sleep 1
done

Adjust CDDEV and TARGET_DIR.

chmod +x autocopy

sudo ./autocopy

This will save any inserted disc (only * and */* files) to the specified location.
The copy is performed by ddrescue, which can recover damaged discs.

jeudi 3 février 2011

How to install a MP210 printer in Ubuntu 10.10 Maverick

Instructions:
  1. Download MP210_debian.tar
  2. Extract it
  3. Follow these instructions to change dependency "libcupsys2" to "libcups2", for each extracted .deb
  4. In a terminal: sudo dpkg -i cnijfilter-common_2.80-1_i386. cnijfilter-mp210series_2.80-1_i386.deb
  5. In a terminal: sudo chown root:root /usr/lib/cups/filter/pstocanonij
That's all!