为什么我的python代码会破坏我的服务器?

时间:2015-01-24 05:20:20

标签: python linux cpu syslog

我是python的新手,我正在尝试编写自己的syslog程序。我在自己的机器上测试了这个,它工作正常,我没有注意到任何事情。现在,当我把它放在我的Ubuntu VM上时,CPU(由顶级'和vSphere报告)达到80-99%。我从i5(3.1 GHz)处理器分配了1个CPU内核。如果有的话,也许文件的打开和关闭会导致这个峰值,但这并不能加起来。在此先感谢您的帮助!

import socket
    log= input("Enter full path of file you would like to monitor:\n")
    host =input("Enter IP address for remote syslog server:\n")
    port =input("Enter syslog service port to send syslogs to:\n")
    port=int(port)
    with open(log,'r') as file:
        current_pos = 0
        data=file.read().splitlines()
        old_len=0
        file.close()

        while True:
            new_len=len(data)
            udp_port = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

            with open(log,'r') as file:
                data=file.read().splitlines()

                while new_len > old_len and current_pos < new_len:
                    msg=data[current_pos]
                    print('Sending....',msg,'=====>',host,':',port)
                    udp_port.sendto(bytes(msg, "utf-8"), (host, port))
                    current_pos+=1

                file.close()#Is this necessary here? 
                old_len=new_len

            #udp_port.shutdown()#stay open only during transmission
            udp_port.close()

1 个答案:

答案 0 :(得分:1)

您的代码有一个while True:块。这意味着它会一遍又一遍地循环,不断地从您的文件中读取。 CPU获得的唯一中断是来自阻塞调用(例如网络和其他I / O),其中线程将产生CPU时间,直到I / O资源可用。

为避免颠覆CPU,您应在sleep()循环结束时加入while来电。即使是10ms的睡眠也应该可以降低延迟,但是可以放松CPU。