Tag: Linux

Env for scripts interpreter searching

Posted by – February 15, 2012

#!/usr/bin/env bash
Probably the most common use of env is to find the correct interpreter
for a script, when the interpreter may be in different directories on
different systems.  The following example will find the `perl’ inter-
preter by searching through the directories specified by PATH.
1.  #!/usr/bin/env perl
One limitation of that example is that it assumes the user’s value for
PATH is set to a value which will find the interpreter you want to exe-
cute.  The -P option can be used to make sure a specific list of directo-
ries is used in the search for utility.  Note that the -S option is also
required for this example to work correctly.
2. #!/usr/bin/env -S -P/usr/local/bin:/usr/bin perl
The above finds `perl’ only if it is in /usr/local/bin or /usr/bin.  That
could be combined with the present value of PATH, to provide more flexi-
bility.  Note that spaces are not required between the -S and -P options:
3. #!/usr/bin/env -S-P/usr/local/bin:/usr/bin:${PATH} perl

#!/usr/bin/env bash
Probably the most common use of env is to find the correct interpreter     for a script, when the interpreter may be in different directories on     different systems.  The following example will find the `perl’ inter-     preter by searching through the directories specified by PATH.
1.  #!/usr/bin/env perl     One limitation of that example is that it assumes the user’s value for     PATH is set to a value which will find the interpreter you want to exe-     cute.  The -P option can be used to make sure a specific list of directo-     ries is used in the search for utility.  Note that the -S option is also     required for this example to work correctly.
2. #!/usr/bin/env -S -P/usr/local/bin:/usr/bin perl
The above finds `perl’ only if it is in /usr/local/bin or /usr/bin.  That     could be combined with the present value of PATH, to provide more flexi-     bility.  Note that spaces are not required between the -S and -P options:
3. #!/usr/bin/env -S-P/usr/local/bin:/usr/bin:${PATH} perl

Env

Posted by – February 15, 2012

#!/usr/bin/env bash
Probably the most common use of env is to find the correct interpreter
for a script, when the interpreter may be in different directories on
different systems.  The following example will find the `perl’ inter-
preter by searching through the directories specified by PATH.
1.  #!/usr/bin/env perl
One limitation of that example is that it assumes the user’s value for
PATH is set to a value which will find the interpreter you want to exe-
cute.  The -P option can be used to make sure a specific list of directo-
ries is used in the search for utility.  Note that the -S option is also
required for this example to work correctly.
2. #!/usr/bin/env -S -P/usr/local/bin:/usr/bin perl
The above finds `perl’ only if it is in /usr/local/bin or /usr/bin.  That
could be combined with the present value of PATH, to provide more flexi-
bility.  Note that spaces are not required between the -S and -P options:
3. #!/usr/bin/env -S-P/usr/local/bin:/usr/bin:${PATH} perl

#!/usr/bin/env bash
Probably the most common use of env is to find the correct interpreter     for a script, when the interpreter may be in different directories on     different systems.  The following example will find the `perl’ inter-     preter by searching through the directories specified by PATH.
1.  #!/usr/bin/env perl     One limitation of that example is that it assumes the user’s value for     PATH is set to a value which will find the interpreter you want to exe-     cute.  The -P option can be used to make sure a specific list of directo-     ries is used in the search for utility.  Note that the -S option is also     required for this example to work correctly.
2. #!/usr/bin/env -S -P/usr/local/bin:/usr/bin perl
The above finds `perl’ only if it is in /usr/local/bin or /usr/bin.  That     could be combined with the present value of PATH, to provide more flexi-     bility.  Note that spaces are not required between the -S and -P options:
3. #!/usr/bin/env -S-P/usr/local/bin:/usr/bin:${PATH} perl

Using tar together with gzip

Posted by – September 22, 2011

How can I extract a tar.gz or .tgz file?
Files with extension tar.gz or .tgz are tar files compressed with gzip. On Unix extract them with:

gunzip < file.tar.gz | tar xvf –
gunzip < file.tgz    | tar xvf –
Can gzip compress several files into a single archive?
Not directly. You can first create a tar file then compress it:

tar cvf –  filenames | gzip > file.tar.gz

stty 显示和修改终端行设置

Posted by – September 13, 2011

学习和转载与: http://codingstandards.iteye.com/blog/826924

用途说明

stty命令用于显示和修改终端行设置(change and print terminal line settings)。

常用参数

stty命令不带参数可以打印终端行设置,加上-a参数可以打印得更详细些。

stty size可以显示终端的大小,即行数和列数。

stty命令还可以更改终端行的设置,格式如下:

stty SETTING CHAR

其中,SETTING可以是如下

eof : 输入结束,文件结束,默认为Ctrl+D。比如:用cat >file来创建文件时,按Ctrl+D来结束输入。
erase : 向后删除字符,擦除最后一个输入字符,默认为Ctrl+?。注意默认情况下退格键Backspace不是删除字符。
intr : 中断当前程序,默认为Ctrl+C。
kill : 删除整条命令,删除整行,默认为Ctrl+U。
quit :退出当前程序,默认为Ctrl+\或Ctrl+|。
start : 启动屏幕输出,默认为Ctrl+Q。
stop :停止屏幕输出,默认为Ctrl+S。有时候终端突然僵死了,可能是不小心按了Ctrl+S的缘故,因为我们习惯性的按Ctrl+S来保存文件。
susp : terminal stop当前程序,默认为Ctrl+Z。这样当前进程就会变成后台进程了。

werase:删除最后一个单词,默认为Ctrl+W。

stty命令还有一些其他用法,如:

stty -echo 关闭回显。比如在脚本中用于输入密码时。

stty echo 打开回显。

输入密码的脚本片段:stty -echo; read var; stty echo; 或 read -s var

使用示例

示例一 打印终端行设置

[root@web ~]# stty
speed 38400 baud; line = 0;
-brkint -imaxbel
[root@web ~]# stty -a
speed 38400 baud; rows 41; columns 132; line = 0;
intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>; eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S;
susp = ^Z; rprnt = ^R; werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0;
-parenb -parodd cs8 -hupcl -cstopb cread -clocal -crtscts -cdtrdsr
-ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl ixon -ixoff -iuclc -ixany -imaxbel -iutf8
opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
isig icanon iexten echo echoe echok -echonl -noflsh -xcase -tostop -echoprt echoctl echoke

[root@web ~]#

示例二 打印当前终端的大小(行数和列数)

[root@web ~]# stty size
41 132

示例三 设置退格键Backspace的删除行为

在默认情况下,我们按退格键Backspace时,会在屏幕上回显^H,而不是把前一个字符删除。比如使用sftp/ftp/sqlplus/ij等命令时,就会碰到这种情况。我们可以使用stty命令把Backspace的行为变成删除前一个字符。

[root@web ~]# sftp 192.168.6.12
Connecting to 192.168.6.12…
root@192.168.6.12’s password:
sftp> get abc^H^H^H^H
Couldn’t stat remote file: No such file or directory
File “/root” not found.
sftp> quit
[root@web ~]#
[root@web ~]# stty erase ^H
[root@web ~]# sftp 192.168.6.12
Connecting to 192.168.6.12…
root@192.168.6.12’s password:
sftp> get abc
Couldn’t stat remote file: No such file or directory
File “/root/abc” not found.
sftp> quit
[root@web ~]#

示例四 在vi编辑文件时按Ctrl+Q来结束终端僵死的局面

[root@web ~]# vi 1.txt
1
2
3
Ctrl+S
~

注:按了Ctrl+S之后,就会禁止屏幕输出,从而出现终端僵死的情况。

这个时候,只要按Ctrl+Q就会结束这种局面,因为它会允许屏幕输出。

Ctrl+Q

示例五 在bash脚本中与tty命令配合使用

在下面的脚本中,先取得终端文件名称,以判断脚本是否运行在交互式方式还是在管道方式。

Bash代码  收藏代码
  1. #!/bin/sh
  2. CONSOLE_INPUT=$(tty)
  3. echo “CONSOLE_INPUT=$CONSOLE_INPUT”
  4. COMMAND_LINE=”java -Xmx640m -classpath .:lib/hyjc.jar:lib/log4j-1.2.15.jar:lib/commons-logging-1.1.1.jar:lib/proxool-0.9.0RC3.jar:lib/mysql-connector-java-5.1.10-bin.jar:lib/poi-3.5-ZHY-20091107.jar:lib/jdom-1.1.jar hyjc.sql.DBCLI MhrDB.properties MhrDB”
  5. if [ “$CONSOLE_INPUT” == “not a tty” ]; then
  6. $COMMAND_LINE
  7. elif [ “$(whereis rlwrap)” == “rlwrap:” ]; then
  8. stty erase ^H
  9. $COMMAND_LINE
  10. else
  11. rlwrap -f jdb.rlwrap $COMMAND_LINE
  12. fi

Bash Colors

Posted by – June 20, 2011

Bash Color Escape Codes

Echo (echo -e) the following escape codes inside \e[ESCCODEm to colorize text in Bash:

  • Black 0;30
  • Dark Gray 1;30
  • Blue 0;34
  • Light Blue 1;34
  • Green 0;32
  • Light Green 1;32
  • Cyan 0;36
  • Light Cyan 1;36
  • Red 0;31
  • Light Red 1;31
  • Purple 0;35
  • Light Purple 1;35
  • Brown 0;33
  • Yellow 1;33
  • Light Gray 0;37
  • White 1;37

Make sure to use echo -e to enable interpretation of backslash escapes:

bash$ echo -e "This is red->\e[00;31mRED\e[00m"

Remove Color

Echo \e[00m to remove text color modifications:

bash$ echo -n '\e[00m'

Linux All Man page

Posted by – August 12, 2010

Login into http://www.tin.org/bin/allman.cgi

Linux下C取得磁盘空间信息

Posted by – August 11, 2010

#include “sys/vfs.h”

struct statfs * buf;
int b = statfs( “/dev”, buf );

if ( ! b )  {
printf( “free space: %u Kbytes”, buf->f_bfree * 4 );
}
else {
printf( ” Failed “);
}

Refers to:

http://blog.chinaunix.net/u1/44301/showart_2086603.html

先说statfs结构:

#include <sys/vfs.h>    /* 或者 <sys/statfs.h> */

int statfs(const char *path, struct statfs *buf);
int fstatfs(int fd, struct statfs *buf);

参数:
path: 位于需要查询信息的文件系统的文件路径名。
fd: 位于需要查询信息的文件系统的文件描述词。
buf:以下结构体的指针变量,用于储存文件系统相关的信息

struct statfs {
long    f_type;     /* 文件系统类型  */
long    f_bsize;    /* 经过优化的传输块大小  */
long    f_blocks;   /* 文件系统数据块总数 */
long    f_bfree;    /* 可用块数 */
long    f_bavail;   /* 非超级用户可获取的块数 */
long    f_files;    /* 文件结点总数 */
long    f_ffree;    /* 可用文件结点数 */
fsid_t  f_fsid;     /* 文件系统标识 */
long    f_namelen;  /* 文件名的最大长度 */
};

statfs结构中可用空间块数有两种f_bfree和 f_bavail,前者是硬盘所有剩余空间,后者为非root用户剩余空间,ext3文件系统给root用户分有5%的独享空间,所以这里是不同的地方。 这里要强调的是每块的大小一般是4K。因此,要实现与df结果一致的就得在获得块数上乘以4,这样已用、可用、总块数就可以实现。如果还要实现百分比一 致,那么要注意的是,df命令获得是整数百分比,没有小数,这里使用的进一法,而不是四舍五入法。所以在程序里直接+1取整。

下面是实现的一个例子:(home目录为一个独立分区)

#include <stdio.h>
#include <sys/vfs.h>

int main()
{
struct statfs sfs;
int i = statfs(“/home”, &sfs);
int percent = (sfs.f_blocks – sfs.f_bfree ) * 100 / (sfs.f_blocks – sfs.f_bfree + sfs.f_bavail) + 1;
printf(“/dev/sda11            %ld    %ld  %ld   %d%% /home\n”,
4*sfs. f_blocks, 4*(sfs.f_blocks – sfs.f_bfree),      4*sfs.f_bavail, percent);
system(“df /home “);
return 0;

}

执行结果:
leave@LEAVE:~/test$ gcc -o df df.c
leave@LEAVE:~/test$ ./df
/dev/sda11            42773008    540356  40059864   2% /home
文件系统           1K-块        已用     可用 已用% 挂载点
/dev/sda11            42773008    540356  40059864   2% /home
leave@LEAVE:~/test$

Gnome Nanny, a Parental Control System for Linux

Posted by – May 25, 2010

Gnome Nanny, a Parental Control System for Linux

Refers to:
http://linuxers.org/article/gnome-nanny-parental-control-system-linux

nanny logo

I am not in favour of monitored or filtered Internet at all. I love Internet the way it is and I hate if someone tries to censor it. But we have to admit that there is a lot of bad stuff on the Internet that you definitely don’t want little kids to come across. Gnome Nanny is a parental control system build for this purpose. Not just the websites, it can also be used to monitor and control the time spent on web or chatting.

Features

  • You can easily control what the kids/users are doing on the computer.
  • How long a user can be using the compuer, browse the web, email and instant message.
  • You can decide the time of the day you want them to do these things.
  • You can even filter out the web pages seen by each of the user by blocking undesirable websites.
  • Its really easy to understand and configure.

The most recent version of Nanny available is 2.29.2. No stable version has been released yet.

Download and Install the Latest version of Nanny in Ubuntu

In order to install the latest development release in Ubuntu, you will have to install it using the ppa. You can find the PPA archive of Nanny here. Follow the instruction in this howto to install nanny in Ubuntu from the PPA. In case of any trouble, leave a comment.

Other distro users may install the source packages from their download page and give it a try.

After installation you can find it at System -> Administration -> Parental Control.

How to Configure Nanny

Understanding the working of Nanny is really easy. Its developers have worked pretty well to improve its usability. In the first glance, you will easily understand how to use it. You can find it in System -> Administration -> Parental control.

With these bars(click them), you can select which part of the day you want a particular service to be active. Different services are mentioned in separate tabs. Just check the option above to activate any option.

Nanny’s Web Content Filtering System

If you want to control the websites that can be accessed you can easily do that by maintaining lists of allowed and blocked sites. Check the enable web filtering box in the web browser tab and click configure.

You can even download the list of blacklisted websites from internet and ofcouse manual addition is available.

Limitations of Nanny

Nanny is a pretty good software and probably the only Parental control system for Linux I know. But it connects the tasks with the respective applicaitons e.g. pidgin with chatting, thunderbird with emails and browser with web surfing. This seems logical but now a days each of these activities are possible on the browser. You can’t expect a 10-12 year old kid to use a mail client . There are tons of social networking sites out there that can keep him “busy”. Although my point seems a little vague here because you can manage and control websites the user can access using Nanny’s web content filtering system.

Another thing I noticed was the applists mentioned in /etc/nanny/applists. It is probably the list of applicaitons supported by Nanny. As of now, or as mentioned in my list, it supports only 3 browsers epiphany, firefox and konqueror. Since, browsing is the most important thing to be censored and monitored here, Nanny should add support for more browsers.

Calling Qt Functions From Unix Signal Handlers

Posted by – May 18, 2010

Home · All Classes · All Functions · Overviews

Calling Qt Functions From Unix Signal Handlers

Refers to:
http://doc.qt.nokia.com/4.6/unix-signals.html
http://www.opengroup.org/onlinepubs/000095399/functions/xsh_chap02_04.html#tag_02_04_01
http://doc.qt.nokia.com/4.6/qsocketnotifier.html
http://doc.qt.nokia.com/4.6/platform-specific.html
You can’t call Qt functions from Unix signal handlers. The standard POSIX rule applies: You can only call async-signal-safe functions from signal handlers. See Signal Actions for the complete list of functions you can call from Unix signal handlers.

But don’t despair, there is a way to use Unix signal handlers with Qt. The strategy is to have your Unix signal handler do something that will eventually cause a Qt signal to be emitted, and then you simply return from your Unix signal handler. Back in your Qt program, that Qt signal gets emitted and then received by your Qt slot function, where you can safely do whatever Qt stuff you weren’t allowed to do in the Unix signal handler.

One simple way to make this happen is to declare a socket pair in your class for each Unix signal you want to handle. The socket pairs are declared as static data members. You also create a QSocketNotifier to monitor the read end of each socket pair, declare your Unix signal handlers to be static class methods, and declare a slot function corresponding to each of your Unix signal handlers. In this example, we intend to handle both the SIGHUP and SIGTERM signals. Note: You should read the socketpair(2) and the sigaction(2) man pages before plowing through the following code snippets.

[cpp]
class MyDaemon : public QObject
{
Q_OBJECT

public:
MyDaemon(QObject *parent = 0, const char *name = 0);
~MyDaemon();

// Unix signal handlers.
static void hupSignalHandler(int unused);
static void termSignalHandler(int unused);

public slots:
// Qt signal handlers.
void handleSigHup();
void handleSigTerm();

private:
static int sighupFd[2];
static int sigtermFd[2];

QSocketNotifier *snHup;
QSocketNotifier *snTerm;
};
[/cpp]

In the MyDaemon constructor, use the socketpair(2) function to initialize each file descriptor pair, and then create the QSocketNotifier to monitor the read end of each pair. The activated() signal of each QSocketNotifier is connected to the appropriate slot function, which effectively converts the Unix signal to the QSocketNotifier::activated() signal.

[cpp]
MyDaemon::MyDaemon(QObject *parent, const char *name)
: QObject(parent,name)
{
if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sighupFd))
qFatal("Couldn’t create HUP socketpair");

if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sigtermFd))
qFatal("Couldn’t create TERM socketpair");
snHup = new QSocketNotifier(sighupFd[1], QSocketNotifier::Read, this);
connect(snHup, SIGNAL(activated(int)), this, SLOT(handleSigHup()));
snTerm = new QSocketNotifier(sigtermFd[1], QSocketNotifier::Read, this);
connect(snTerm, SIGNAL(activated(int)), this, SLOT(handleSigTerm()));


}
[/cpp]

Somewhere else in your startup code, you install your Unix signal handlers with sigaction(2)

[cpp]
static int setup_unix_signal_handlers()
{
struct sigaction hup, term;

hup.sa_handler = MyDaemon::hupSignalHandler;
sigemptyset(&hup.sa_mask);
hup.sa_flags = 0;
hup.sa_flags |= SA_RESTART;

if (sigaction(SIGHUP, &hup, 0) > 0)
return 1;

term.sa_handler = MyDaemon::termSignalHandler;
sigemptyset(&term.sa_mask);
term.sa_flags |= SA_RESTART;

if (sigaction(SIGTERM, &term, 0) > 0)
return 2;

return 0;
}
[/cpp]

In your Unix signal handlers, you write a byte to the write end of a socket pair and return. This will cause the corresponding QSocketNotifier to emit its activated() signal, which will in turn cause the appropriate Qt slot function to run.

[cpp]
void MyDaemon::hupSignalHandler(int)
{
char a = 1;
::write(sighupFd[0], &a, sizeof(a));
}

void MyDaemon::termSignalHandler(int)
{
char a = 1;
::write(sigtermFd[0], &a, sizeof(a));
}
[/cpp]

In the slot functions connected to the QSocketNotifier::activated() signals, you read the byte. Now you are safely back in Qt with your signal, and you can do all the Qt stuff you weren’tr allowed to do in the Unix signal handler.

[cpp]
void MyDaemon::handleSigTerm()
{
snTerm->setEnabled(false);
char tmp;
::read(sigtermFd[1], &tmp, sizeof(tmp));

// do Qt stuff

snTerm->setEnabled(true);
}

void MyDaemon::handleSigHup()
{
snHup->setEnabled(false);
char tmp;
::read(sighupFd[1], &tmp, sizeof(tmp));

// do Qt stuff

snHup->setEnabled(true);
}
[/cpp]

Video for Linux Two API Specification

Posted by – May 12, 2010

Refers to:
http://linux.bytesex.org/
http://v4l2spec.bytesex.org/spec/
http://v4l2spec.bytesex.org/
http://linuxtv.org/downloads/video4linux/API/V4L1_API.html

V4L2 API Specification (Revision 0.24)

V4L2 Mini-FAQ

Q: That’s the V4L2 spec, what about V4L?
A: /usr/src/linux/Documentation/video4linux/API.html
and http://linuxtv.org/downloads/video4linux/API/V4L1_API.html

Q: Are there any examples?
A: Yes, in the spec. Also a complete video capture example, source is capture.c.

Q: I have more questions.
A: Try the V4L Wiki or the Video4Linux mailing list.