顯示具有 雜亂小程式 標籤的文章。 顯示所有文章
顯示具有 雜亂小程式 標籤的文章。 顯示所有文章

2008年7月16日 星期三

IPC

估唔到, 畢左業咁耐都要找返d 書出來. 因為最近收到一個 support call, 同事想o係佢個程式裡面呼叫另一個程式, 然後向該程式詢問數次, 並用其回覆進行運算. 而被呼叫果個程式係起動得好慢同時會佔用很多資源, 並且會以"亙動模式"運行. 同事唔希望每一次詢問都重新呼叫一次, 因為咁樣做會好慢, 唯有做 IPC 啦.
咁個 call 就送左過來, 我便用 pipe() 寫了一個好簡單 IPC o既例子比佢, 呼叫 ed, 行句指令再叫佢結束. 其實, 而家學校仲有冇教 IPC o既呢?

p.c

#include <stdio.h>
#include <sys/types.h>
main()
{
pid_t pid;
int rval;
int pta[2]; // parent stdout, child stdin
int ptb[2]; // parent stdin, child stderr
char pres[250];

// Create pipes
if ( pipe(pta) )
{
fprintf(stderr,"create pipe A error!\n");
exit(1);
}
if ( pipe(ptb) )
{
fprintf(stderr,"create pipe B error!\n");
exit(1);
}
// fork process
if ( (pid=fork()) == -1 )
{
fprintf(stderr,"fork error\n");
exit(1);
}

if ( pid )
{
// parent side

dup2(pta[1],1); // replace stdout with pipe
dup2(ptb[0],0); // replace stdin with pipe
setvbuf(stdout,(char*)NULL,_IONBF,0); // set non-buffered output on stdout

sleep(2);
printf("l\n");

fgets(pres,sizeof(pres),stdin);
fprintf(stderr,"output of child from pipe : %s\n",pres);

if ( strncmp(pres,"?",1) == 0 )
{
printf("q\n");
}
else
{
fprintf(stderr,"Error : Unknown output from child.\n");
exit(1);
}

wait(&rval); // wait for child process
fprintf(stderr,"child process exited -- %d\n",rval);

}
else
{
// child side
dup2(pta[0],0); // replace stdin with pipe
dup2(ptb[1],2); // replace stderr with pipe, as the output of our command in ed is out to stderr
// use dup2(ptb[1],1); if replace stdout with pipe

// call external porgram ed
if ( execl("/bin/ed","ed",NULL) == -1 )
{
fprintf(stderr,"call external program error");
exit(1);
}
}
}

2008年6月27日 星期五

gtk dialog box test

用 gtk 開個 "yes,no" dialog box.
compile by : cc -o d_box -I/usr/include/gtk-1.2 -I/usr/include/glib-1.2 -I/usr/lib/glib/include -I/usr/X11R6/include -L/usr/lib -L/usr/X11R6/lib -lgtk -lgdk -rdynamic -lgmodule -lglib -ldl -lXi -lXext -lX11 -lm d_box.c


#include <stdio.h>
#include <gtk/gtk.h>

void ButtonClicked(GtkWidget *widget, gpointer data);

int main(int argc, char *argv[])
{
GtkWidget *window, *yes, *no, *basebox, *hbox, *tbox;
GtkWidget *lbox;
char mesg[512];

if (argc != 2)
{
fprintf(stderr,"Usage : %s \n",argv[0]);
exit(-1);
}

gtk_set_locale();
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window),"Dialog box test");
gtk_window_set_default_size(GTK_WINDOW(window),400,100);
gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER);
gtk_signal_connect(GTK_OBJECT(window),"destroy",GTK_SIGNAL_FUNC(gtk_main_quit), NULL);
basebox = gtk_vbox_new(TRUE,0);
hbox = gtk_hbox_new(TRUE,0);
gtk_box_pack_start(GTK_BOX(basebox), hbox, FALSE, TRUE, 0);
tbox = gtk_hbutton_box_new();
gtk_box_pack_start(GTK_BOX(basebox), tbox, FALSE, TRUE, 0);
sprintf(mesg,"%s",argv[1]);
lbox = gtk_label_new(mesg);
gtk_box_pack_start(GTK_BOX(hbox), lbox, FALSE, TRUE, 0);
gtk_button_box_set_layout(GTK_BUTTON_BOX(tbox),GTK_BUTTONBOX_SPREAD);
gtk_button_box_set_child_size(GTK_BUTTON_BOX(tbox),50,16);
yes = gtk_button_new_with_label("Yes");
gtk_container_add(GTK_CONTAINER(tbox), yes);
gtk_signal_connect(GTK_OBJECT(yes), "clicked", GTK_SIGNAL_FUNC(ButtonClicked), "yes");
no = gtk_button_new_with_label("No");
gtk_container_add(GTK_CONTAINER(tbox), no);
gtk_signal_connect(GTK_OBJECT(no), "clicked", GTK_SIGNAL_FUNC(ButtonClicked), "no");
gtk_container_add(GTK_CONTAINER(window), basebox);
gtk_window_set_focus(GTK_WINDOW(window),yes);
gtk_widget_show_all(window);
gtk_main();
return(0);
}

void ButtonClicked(GtkWidget *widget, gpointer data)
{
if (g_strcasecmp(data, "yes") == 0)
{
printf("0\n");
}
else
{
printf("1\n");
}

gtk_main_quit();
}

2008年6月25日 星期三

tracker_write

為免 i/o buffer 令一些 tracking message 印唔切, 寫了個用 fflush 清 stdout buffer o既 program 比 script 呼叫.


#include <stdio.h>
#include <time.h>

int main(int argc, char *argv[])
{
FILE *fp;
int pres;

time_t now;
struct tm *stime;
char timeval[20];

if (argc < 3)
{
fprintf(stderr,"%s \n",argv[0]);
exit(-1);
}

if (fp = fopen(argv[1],"a"))
{
now = time(NULL);
stime = localtime(&now);
sprintf(timeval,"%d%02d%02d %02d:%02d:%02d",stime->tm_year + 1900,stime->tm_mon + 1,stime->tm_mday,stime->tm_hour,stime->tm_min,stime->tm_sec);

pres = fprintf(fp,"%s %s\n",timeval,argv[2]);
fflush(fp);
fclose(fp);
if (pres < 0)
{
fprintf(stderr,"File %s write error.\n",argv[1]);
}
}
else
{
fprintf(stderr,"File %s could not open.\n",argv[1]);
exit(-1);
}
}

2008年6月22日 星期日

stat test

用 stat 查出檔案的資料.


#!/usr/bin/perl
#
# test stat
#

my $file1 = shift;
if (! (-e $file1))
{
print "Invalid file : $file1\n";
exit(-1);
}

my @t1 = stat($file1);

print "file : $file1 stat result\n";
foreach $line(@t1)
{
print "$line ";
}
print "\n";

my @des;
$des[0]="Device";$des[1]="Inode";$des[2]="Permission";
$des[3]="Links";$des[4]="Uid";$des[5]="Gid";
$des[6]="Device Type";$des[7]="Size";$des[8]="Access";
$des[9]="Modify";$des[10]="Change";$des[11]="IO Block";$des[12]="Blocks";
print "Description\n";
for($i=0;$i<=$#t1;$i++)
{
print "$i : $des[$i] : $t1[$i]\n";
}

exit(0);

2008年6月21日 星期六

check web service

睇下個URL係咪正常去得到.


#!/usr/bin/perl
#
# check web service
#
use strict;
use LWP::Simple;
use URI::URL;

my $url = shift;
if (! ($url) )
{
print "Usage : $0 \n";
exit(-1);
}

# make and check url
my $chkurl = URI::URL->new($url);
my @headers = head($chkurl);
if (@headers)
{
print "Host : $url\n";
print "Server : @{[pop @headers]}\n\n";
}
else
{
print "Unable to retrive @{[$chkurl->as_string]}\n\n";
}

exit(0);

2008年6月19日 星期四

mass_ssh

經由 ssh, 呼叫一定數量機器運行特定指令.


#!/bin/sh
#
# call other machine to exec cmd by ssh
#

# function
exec_cmd()
{
LSUB=$1
IPS=$2
LCMD=$3

CHKRNG=`echo "${IPS}" | grep "-"`

if [ ${CHKRNG} ]; then
OIFS=$IFS
IFS="-"
SIP=
EIP=
for A in ${IPS}
do
if [ ! ${SIP} ]; then
SIP=${A}
else
EIP=${A}
fi
done
IFS=$OIFS

if [[ ${SIP} -gt ${EIP} ]]; then
echo "Start IP : ${SIP} greater than End IP : ${EIP}"
else
CIP=${SIP}
while [[ ${CIP} -le ${EIP} ]]
do
echo "Exec [${LCMD}] on ${LSUB}.${CIP}"
ssh ${LSUB}.${CIP} "$LCMD"
echo
CIP=$(($CIP + 1))
done
fi
else
echo "Exec [${LCMD}] on ${LSUB}.${IPS}"
ssh ${LSUB}.${IPS} "$LCMD"
echo
fi
}


if [[ $# -lt 3 ]]; then
echo "Not enough parameter."
echo "Usage : $0 "
echo "e.g. $0 192.168.0 ls 1 3 5"
exit -1
fi

ALLARGV=$@

if [[ -z ${ALLARGV} ]]; then
echo "Usage : $0 "
echo "e.g. $0 192.168.0 ls 1 3 5"
exit -1
fi

# separate Command and Machine Numbers
SUBNET=$1
CMD=$2
shift 2

if [[ -z "$@" ]]; then
echo "Please input "
echo "e.g $0 192.168.0 \"ls -l\" \"1-3\""
exit -1
fi

for A in $@
do
exec_cmd ${SUBNET} ${A} "${CMD}"
done

exit 0

2008年6月18日 星期三

opening page

讀書時貪得意寫的, 用類似原理, 現在用來做 console program waiting signal.


#include <stdio.h>
#include <termios.h>
#include <unistd.h>

#define COLOR "^[[%d;%dm"
#define POSITION "^[[%d;%df"
#define CLEAR "^[[2J"

struct termios save_termios;

main()
{
op();
printf(CLEAR);
}

tty_reset()
{
if (tcsetattr(STDIN_FILENO,TCSAFLUSH,&save_termios) < 0)
exit(-1);
return(0);
}

tty_cbreak(work,times)
int work;
int times;
{
int i;
char c;
struct termios buf;

if (tcgetattr(STDIN_FILENO,&save_termios)<0)
exit(0);
buf=save_termios;
buf.c_lflag &= ~(ECHO | ICANON);
buf.c_cc[VMIN] = work;
buf.c_cc[VTIME] = times;
if (tcsetattr(STDIN_FILENO,TCSAFLUSH,&buf) < 0)
exit(-1);
return(0);
}

op()
{
int work,times;
int x,y,z;
int cr=30;
int ef=1;
char c=0;

printf(CLEAR);

printf(POSITION,22,5);
printf("^[[5;37mPress any Key to continue!");

work=0;times=1;
tty_cbreak(work,times);

while (c==0)
{
read(STDIN_FILENO,&c,1);
y=1;
for (x=6;x<15;x++)
{
printf(POSITION,x,y++);
if (ef==0)ef=1;else ef=0;
if (cr==38)cr=31;
printf(COLOR,ef,cr++);
printf("VVV");
}
for (x=15;x>5;x--)
{
printf(POSITION,x,y++);
if (ef==0)ef=1;else ef=0;
if (cr==38)cr=31;
printf(COLOR,ef,cr++);
printf("VVV");
}

for (x=0;x<10000;x++)
for (y=0;y<50;y++)
;
}
tty_reset();
}

2008年6月17日 星期二

random number

random 0-9, 其實用 pid / time 其中一個做 seed 都 ok, 不過用 time - pid 都唔算係好花 resource 啊.


#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>

main()
{
int j;
pid_t mypid;
time_t now;

mypid = getpid();
now = time(NULL);

printf("pid = %d\n",mypid);
printf("time = %d\n",now);

srand((int)time - mypid);
j=(int) (10.0*rand()/(RAND_MAX));
printf("j = %d\n",j);

j=(int) (10.0*rand()/(RAND_MAX));
printf("j = %d\n",j);
}

check last local login user

check 下最後 local login 係邊個, print out userid, hostname 同埋現在的時間


#!/bin/sh
#
# check uid and hostname
#
LASTUSER=`last | grep ' :0 '|head -n 1`
if [[ -z ${LASTUSER} ]]
then
LASTUSER=`last -f /var/log/wtmp.1 | grep ' :0 '|head -n 1`
fi

if `test "${LASTUSER}"`
then
LUSER=`echo ${LASTUSER} | awk '{print $1}'`
else
LUSER="nologin"
fi

NOW=`date +%Y%m%d%H%M`
HNAME=`hostname -s`

echo "${LUSER}:${HNAME}:${NOW}"

exit

2008年6月15日 星期日

check cpu usage

grep 個 cpu usage 同埋 uptime 出來, print 去 stdout


#!/usr/bin/perl
#
# Used to check cpu usage and return to stdout
#
$machine = `hostname -s`;
$getcpu = `/usr/bin/sar -u 1 5 | grep Average`;
$getuptime = `/usr/bin/uptime`;

$getcpu =~ /^Average:\s+(\w+)\s+(\d+)\.(\d+)\s+(\d+)\.(\d+)\s+(\d+)\.(\d+)\s+(\d+)\.(\d+)/;
$getcpuusr = $2;
$getcpusys = $6;
print "$getcpuusr\n";
print "$getcpusys\n";

if ($getuptime =~ /^\s+(\d{1,2}:\d{2}:\d{2})\s+up\s+(\d+\s+\w+)/)
{
$utime = $2;
}
else
{
$getuptime =~ /^\s+\d{1,2}:\d{2}:\d{2}\s+up\s+(\d+:\d+)/;
$utime = $1;
}
print "$utime\n";

print "$machine\n";

又係日期時間

真係無乜辦法, 無論用邊隻語言, 都係要砌時間.

localtime.pl

#!/usr/bin/perl
my @now = localtime();

for($i=0;$i <= $#now; $i++)
{
print "$now[$i]\n";
}


timelocal.pl

#!/usr/bin/perl
use Time::Local;

my $offset = shift; $offset = 0 if (!($offset));

my $time = time();
my $ltime = localtime($time);
my ($t0,$t1,$t2,$t3,$t4,$t5) = (localtime($time))[0,1,2,3,4,5];
my $tlime = timelocal($t0,$t1,$t2,$t3,$t4,$t5+1900);

print "$t0,$t1,$t2,$t3,$t4,$t5\n";
print "timestamp = $time\nlocaltime = $ltime\ntimelocal = $tlime\n";

my ($o0,$o1,$o2,$o3,$o4,$o5) = (localtime($time - (86400 * $offset)))[0,1,2,3,4,5];
my $daystart = timelocal(0,0,0,$o3,$o4,$o5+1900);
my $dayend = timelocal(59,59,23,$o3,$o4,$o5+1900);
print "oldday : start = $daystart, end = $dayend\n";

2008年6月13日 星期五

test ldap server auth

無啦啦要 check 下個 ldap auth ok 唔 ok


#!/usr/bin/perl
#
# test ldap call
#
use Authen::Simple::LDAP;

my $ldap = Authen::Simple::LDAP->new(host => '192.168.0.1', basedn => 'ou=People,o=finance,dc=abc,dc=com') or die "$@";

if ($ldap->authenticate('test','ttpasswd'))
{
print "auth ok\n";
}
else
{
print "auth fail\n";
}

顯示時間值


#include <stdio.h>
#include <time.h>

main()
{
time_t now;
char *cnow;
struct tm *stime;
time_t nnow;
time_t mnow;
time_t daystart;

now = time(NULL);
printf("time(NULL) = %d\n",now);

cnow = ctime(&now);
printf("ctime(&now) = %s",cnow);

stime = localtime(&now);
printf("stime : tm_sec = %d, tm_min = %d, tm_hour = %d, tm_mday = %d, tm_mon = %d, tm_year = %d\n",stime->tm_sec,stime->tm_min,stime->tm_hour,stime->tm_mday,stime->tm_mon,stime->tm_year);

nnow = mktime(stime);
printf("nnow = %d\n",nnow);

stime->tm_hour = 0;
stime->tm_min = 0;
stime->tm_sec = 0;

mnow = mktime(stime);
printf("mnow = %d\n",mnow);
}

2008年6月12日 星期四

ascii

唔知點解, 總係有時會拿起手無 ascii table...


#include <stdio.h>

main()
{
int i;
int row = 3;

for(i=0; i<128; i++)
{
printf("%d (%c) ",i,i);
if (i % row == 2){printf("\n");}
}
printf("\n");

}

Hello World

呢個都應該係最多人寫過架喇. 作為第一篇, 甚有意思.


#include <stdio.h>

main()
{
printf("Hello World\n");
}