posts - 18, comments - 1, trackbacks - 0, articles - 0
  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理

2010年8月27日

代码
import sys, os    
def main():   
    
""" A demo daemon main routine, write a datestamp to   
        /tmp/daemon-log every 10 seconds.  
    
"""  
    import time   
    f 
= open("/tmp/daemon-log""w")    
    
while 1:    
        f.write(
'%s\n' % time.ctime(time.time()))    
        f.flush()    
        time.sleep(
10)    
if __name__ == "__main__":   
    # 
do the UNIX double-fork magic, see Stevens' "Advanced    
    # Programming in the UNIX Environment" for details (ISBN 0201563177)   
    try:    
        pid 
= os.fork()    
        
if pid > 0:   
            # exit first parent   
            sys.exit(
0)    
    except OSError, e:    
        print 
>>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror)    
        sys.exit(
1)   
    # decouple from parent environment   
    os.chdir(
"/")    
    os.setsid()    
    os.umask(
0)    
    # 
do second fork   
    
try:    
        pid 
= os.fork()    
        
if pid > 0:   
            # exit from second parent, print eventual PID before   
            print 
"Daemon PID %d" % pid    
            sys.exit(
0)    
    except OSError, e:    
        print 
>>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)    
        sys.exit(
1)    
    # start the daemon main loop   
    main()   

 

以上代码中main()函数包括了一个永久循环过程:把时间戳写入一个文件。

运行的时候,建立一个进程,linux会分配个进程号。然后调用os.fork()创建子进程。若pid>0就是自己,自杀。子进程跳过if语句,通过os.setsid()成为linux中的独立于终端的进程(不响应sigint,sighup等)。

第二次os.fork再创建一个子进程,自己自杀。原因是os.setsid()后成为父进程,虽然已经不被动响应信号,但访问终端文件时控制权还是会失去。这次创建的进程真的是孤魂野鬼的daemon,并且外界对它影响被控制在最小。

代码来自:http://code.activestate.com/recipes/66012/download/1/

posted @ 2010-08-27 22:07 月光林地 阅读(482) 评论(0) 编辑

有时候因为一些情况,需要把 linux 下符合某一项条件的所有进程 kill 掉,又不能用 killall 直接杀掉某一进程名称包含的所有运行中进程(我们可能只需要杀掉其中的某一类或运行指定参数命令的进程),这个时候我们需要运用 ps, grep, cut kill 一起操作。

ok,下面给出具体的参考:

ps -ef|grep LOCAL=NO|grep -v grep|cut -c 9-15|xargs kill -9

运行这条命令将会杀掉所有含有关键字"LOCAL=NO"的进程,是不是很方便?

下面将这条命令作一下简单说明:

管道符"|"用来隔开两个命令,管道符左边命令的输出会作为管道符右边命令的输入。

"ps -ef" 是linux里查看所有进程的命令。这时检索出的进程将作为下一条命令"grep LOCAL=NO"的输入。

"grep LOCAL=NO" 的输出结果是,所有含有关键字"LOCAL=NO"的进程。

"grep -v grep" 是在列出的进程中去除含有关键字"grep"的进程。

"cut -c 9-15" 是截取输入行的第9个字符到第15个字符,而这正好是进程号PID。

"xargs kill -9" 中的 xargs 命令是用来把前面命令的输出结果(PID)作为"kill -9"命令的参数,并执行该命令。"kill -9"会强行杀掉指定进程。

其它类似的情况,只需要修改"grep LOCAL=NO"中的关键字部分就可以了。

另一种方法,使用awk

ps x|grep gas|grep -v grep |awk '{print $1}'|xargs kill -9

posted @ 2010-08-27 22:01 月光林地 阅读(1015) 评论(0) 编辑

2010年3月21日

list<int> l;
 for(int i = 0; i<10; i++)
 {
  l.push_back(i);
 }

 
 for(list<int>::reverse_iterator it = l.rbegin(); it != l.rend();)
 {
  cout<<*it<<endl;
  it = list<int>::reverse_iterator(l.erase((++it).base()));
  
 }

posted @ 2010-03-21 18:22 月光林地 阅读(193) 评论(0) 编辑

2010年1月8日

QueryPerformanceCounter()这个函数返回高精确度性能计数器的值,它可以以微妙为单位计时.但是QueryPerformanceCounter()确切的精确计时的最小单位是与系统有关的,所以,必须要查询系统以得到QueryPerformanceCounter()  返回的嘀哒声的频率.

QueryPerformanceFrequency()提供了这个频率值,返回每秒嘀哒声的个数.

计算确切的时间是从第一次调用QueryPerformanceCounter()开始的假设得到的LARGE_INTEGER   为nStartCounter,过一段时间后再次调用该函数结束的,设得到nStopCounter.两者之差除以QueryPerformanceFrequency()的频率就是开始到结束之间的秒数.由于计时函数本身要耗费很少的时间,要减去一个很少的时间开销.但一般都把这个开销忽略.

公式如下:       
 double   elapse = (double)(nStopCounter.QuadPart-nStartCounter.QuadPart)/frequency.QuadPart    (计算结果单位为秒)

 

 

QueryPerformanceFrequency() - 基本介绍

类型:Win32API

原型:BOOL QueryPerformanceFrequency(LARGE_INTEGER *lpFrequency);

作用:返回硬件支持的高精度计数器的频率。

返回值:非零,硬件支持高精度计数器;零,硬件不支持,读取失败。

QueryPerformanceFrequency() - 技术特点

供WIN9X使用的高精度定时器:QueryPerformanceFrequency()和QueryPerformanceCounter(),要求计算机从硬件上支持高精度定时器。

函数的原形是:

  BOOL QueryPerformanceFrequency(LARGE_INTEGER *lpFrequency);

  BOOL QueryPerformanceCounter (LARGE_INTEGER *lpCount);

 

数据类型LARGEINTEGER既可以是一个作为8字节长的整数,也可以是作为两个4字节长的整数的联合结构,其具体用法根据编译器是否支持64位而定。该类型的定义如下:

  typeef union _ LARGE_INTEGER

  {

   struct

   {

   DWORD LowPart;

   LONG HighPart;

   };

   LONGLONG QuadPart;

  } LARGE_INTEGER;


 

posted @ 2010-01-08 10:59 月光林地 阅读(213) 评论(0) 编辑

2009年11月10日

假如有bmp1和bmp2两个bitmapdata对象,现在要把bmp2中(sourceX,sourceY,sourceX+width,sourceY+height)区域缩放scale倍后画到bmp1的(targetX,targetY)位置,则参数设置为:

bmp1.draw(bmp2, new Matrix(scale, 0, 0, scale, targetX-sourceX*scale, targetY-sourceY*scale), null, null, new Rectangle(targetX, targetY, width*scale, height*scale), false);

posted @ 2009-11-10 11:44 月光林地 阅读(418) 评论(0) 编辑

2009年10月18日

Solution 1 (2D)

The following is a simple solution to the problem often encountered in computer graphics, determining whether or not a point (x,y) lies inside or outside a 2D polygonally bounded plane. This is necessary for example in applications such as polygon filling on raster devices. hatching in drafting software, and determining the intersection of multiple polygons.

Consider a polygon made up of N vertices (xi,yi) where i ranges from 0 to N-1. The last vertex (xN,yN) is assumed to be the same as the first vertex (x0,y0), that is, the polygon is closed. To determine the status of a point (xp,yp) consider a horizontal ray emanating from (xp,yp) and to the right. If the number of times this ray intersects the line segments making up the polygon is even then the point is outside the polygon. Whereas if the number of intersections is odd then the point (xp,yp) lies inside the polygon. The following shows the ray for some sample points and should make the technique clear.

 

Note: for the purposes of this discussion 0 will be considered even, the test for even or odd will be based on modulus 2, that is, if the number of intersections modulus 2 is 0 then the number is even, if it is 1 then it is odd.

The only trick is what happens in the special cases when an edge or vertex of the polygon lies on the ray from (xp,yp). The possible situations are illustrated below.

 

The thick lines above are not considered as valid intersections, the thin lines do count as intersections. Ignoring the case of an edge lying along the ray or an edge ending on the ray ensures that the endpoints are only counted once.

Note that this algorithm also works for polygons with holes as illustrated below

 

The following C function returns INSIDE or OUTSIDE indicating the status of a point P with respect to a polygon with N points.

#define MIN(x,y) (x < y ? x : y)
#define MAX(x,y) (x > y ? x : y)
#define INSIDE 0
#define OUTSIDE 1

typedef struct {
   double x,y;
} Point;

int InsidePolygon(Point *polygon,int N,Point p)
{
  int counter = 0;
  int i;
  double xinters;
  Point p1,p2;

  p1 = polygon[0];
  for (i=1;i<=N;i++) {
    p2 = polygon[i % N];
    if (p.y > MIN(p1.y,p2.y)) {
      if (p.y <= MAX(p1.y,p2.y)) {
        if (p.x <= MAX(p1.x,p2.x)) {
          if (p1.y != p2.y) {
            xinters = (p.y-p1.y)*(p2.x-p1.x)/(p2.y-p1.y)+p1.x;
            if (p1.x == p2.x || p.x <= xinters)
              counter++;
          }
        }
      }
    }
    p1 = p2;
  }

  if (counter % 2 == 0)
    return(OUTSIDE);
  else
    return(INSIDE);
}

The following code is by Randolph Franklin, it returns 1 for interior points and 0 for exterior points.

int pnpoly(int npol, float *xp, float *yp, float x, float y)
    {
      int i, j, c = 0;
      for (i = 0, j = npol-1; i < npol; j = i++) {
        if ((((yp[i] <= y) && (y < yp[j])) ||
             ((yp[j] <= y) && (y < yp[i]))) &&
            (x < (xp[j] - xp[i]) * (y - yp[i]) / (yp[j] - yp[i]) + xp[i]))
          c = !c;
      }
      return c;
    }

Contribution by Alexander Motrichuk - InsidePolygonWithBounds.cpp.
Quote: "For most of the algorithms above there is a pathological case if the point being queried lies exactly on a vertex. The easiest way to cope with this is to test that as a separate process and make your own decision as to whether you want to consider them inside or outside."

Solution 2 (2D)

Another solution forwarded by Philippe Reverdy is to compute the sum of the angles made between the test point and each pair of points making up the polygon. If this sum is 2pi then the point is an interior point, if 0 then the point is an exterior point. This also works for polygons with holes given the polygon is defined with a path made up of coincident edges into and out of the hole as is common practice in many CAD packages.

The inside/outside test might then be defined in C as
typedef struct {
   int h,v;
} Point;

int InsidePolygon(Point *polygon,int n,Point p)
{
   int i;
   double angle=0;
   Point p1,p2;

   for (i=0;i<n;i++) {
      p1.h = polygon[i].h - p.h;
      p1.v = polygon[i].v - p.v;
      p2.h = polygon[(i+1)%n].h - p.h;
      p2.v = polygon[(i+1)%n].v - p.v;
      angle += Angle2D(p1.h,p1.v,p2.h,p2.v);
   }

   if (ABS(angle) < PI)
      return(FALSE);
   else
      return(TRUE);
}

/*
   Return the angle between two vectors on a plane
   The angle is from vector 1 to vector 2, positive anticlockwise
   The result is between -pi -> pi
*/
double Angle2D(double x1, double y1, double x2, double y2)
{
   double dtheta,theta1,theta2;

   theta1 = atan2(y1,x1);
   theta2 = atan2(y2,x2);
   dtheta = theta2 - theta1;
   while (dtheta > PI)
      dtheta -= TWOPI;
   while (dtheta < -PI)
      dtheta += TWOPI;

   return(dtheta);
}

Solution 3 (2D)

There are other solutions to this problem for polygons with special attributes. If the polygon is convex then one can consider the polygon as a "path" from the first vertex. A point is on the interior of this polygons if it is always on the same side of all the line segments making up the path.

Given a line segment between P0 (x0,y0) and P1 (x1,y1), another point P (x,y) has the following relationship to the line segment.

Compute
(y - y0) (x1 - x0) - (x - x0) (y1 - y0)

 

if it is less than 0 then P is to the right of the line segment, if greater than 0 it is to the left, if equal to 0 then it lies on the line segment.

Solution 4 (3D)

This solution was motivated by solution 2 and correspondence with Reinier van Vliet and Remco Lam. To determine whether a point is on the interior of a convex polygon in 3D one might be tempted to first determine whether the point is on the plane, then determine it's interior status. Both of these can be accomplished at once by computing the sum of the angles between the test point (q below) and every pair of edge points p[i]->p[i+1]. This sum will only be 2pi if both the point is on the plane of the polygon AND on the interior. The angle sum will tend to 0 the further away from the polygon point q becomes.

The following code snippet returns the angle sum between the test point q and all the vertex pairs. Note that the angle sum is returned in radians.

typedef struct {
   double x,y,z;
} XYZ;
#define EPSILON  0.0000001
#define MODULUS(p) (sqrt(p.x*p.x + p.y*p.y + p.z*p.z))
#define TWOPI 6.283185307179586476925287
#define RTOD 57.2957795

double CalcAngleSum(XYZ q,XYZ *p,int n)
{
   int i;
   double m1,m2;
   double anglesum=0,costheta;
   XYZ p1,p2;

   for (i=0;i<n;i++) {

      p1.x = p[i].x - q.x;
      p1.y = p[i].y - q.y;
      p1.z = p[i].z - q.z;
      p2.x = p[(i+1)%n].x - q.x;
      p2.y = p[(i+1)%n].y - q.y;
      p2.z = p[(i+1)%n].z - q.z;

      m1 = MODULUS(p1);
      m2 = MODULUS(p2);
      if (m1*m2 <= EPSILON)
         return(TWOPI); /* We are on a node, consider this inside */
      else
         costheta = (p1.x*p2.x + p1.y*p2.y + p1.z*p2.z) / (m1*m2);

      anglesum += acos(costheta);
   }
   return(anglesum);
}
Note

For most of the algorithms above there is a pathological case if the point being queries lies exactly on a vertex. The easiest way to cope with this is to test that as a separate process and make your own decision as to whether you want to consider them inside or outside.

posted @ 2009-10-18 23:56 月光林地 阅读(647) 评论(0) 编辑

2009年10月17日

摘要: 正多边形画法:[代码]正六边形网格画法:[代码]阅读全文

posted @ 2009-10-17 23:47 月光林地 阅读(534) 评论(0) 编辑

2009年8月4日

摘要: <effective c++> 第二十条:<宁以pass-by-reference-to-const 替换 pass-by-value> 里说到当参数是内置类型、STL、函数对象时,pass by value 往往比 pass by reference 的效率高。第一次看到函数对象的概念,于是去查了一下google,原来以前接触过的#_#!!!,如callback函数。相关...阅读全文

posted @ 2009-08-04 00:47 月光林地 阅读(281) 评论(0) 编辑

2009年7月23日

摘要: CloseHandle()函数的使用:很多程序在创建线程都这样写的:............ThreadHandle = CreateThread(NULL,0,.....);CloseHandel(ThreadHandle );。。。。。这不是刚好创建又关闭了吗?线程怎么运行呢?================================================Closing a t...阅读全文

posted @ 2009-07-23 15:04 月光林地 阅读(123) 评论(0) 编辑

2009年7月22日

摘要: 写出一个struct,然后sizeof,你会不会经常对结果感到奇怪?sizeof的结果往往都比你声明的变量总长度要大,这是怎么回事呢?讲讲字节对齐吧./******************************分割线如果体系结构是不对齐的,A中的成员将会一个挨一个存储,从而sizeof(a)为11。显然对齐更浪费了空间。那么为什么要使用对齐呢?体系结构的对齐和不对齐,是在时间和空间上的一个权衡。...阅读全文

posted @ 2009-07-22 11:18 月光林地 阅读(73) 评论(0) 编辑