import socket,struct,time,threading,os
def enc(p):
    r=b''
    for k,v in p.items():
        for b in (k.encode(),v.encode()):
            if len(b)<128: r+=struct.pack('B',len(b))
            else: r+=struct.pack('!I',len(b)|0x80000000)
        r+=k.encode()+v.encode()
    return r
def req():
    p={'GATEWAY_INTERFACE':'CGI/1.1','REQUEST_METHOD':'GET','SCRIPT_FILENAME':'/tmp/t1.php','SCRIPT_NAME':'/x.php','REQUEST_URI':'/x.php','QUERY_STRING':'','SERVER_PROTOCOL':'HTTP/1.1','REMOTE_ADDR':'127.0.0.1','SERVER_NAME':'localhost','SERVER_PORT':'80','SERVER_ADDR':'127.0.0.1','REDIRECT_STATUS':'200','DOCUMENT_ROOT':'/','HTTP_HOST':'localhost'}
    begin=struct.pack('!BBHH',1,1,1,3)+struct.pack('!HB',1,0)
    pd=enc(p)
    out=begin+struct.pack('!BBHH',1,4,1,len(pd))+pd+struct.pack('!BBHH',1,4,1,0)+struct.pack('!BBHH',1,5,1,0)
    try:
        s=socket.create_connection(('127.0.0.1',9000),4)
        s.sendall(out); s.settimeout(5)
        try:
            while True:
                c=s.recv(65536)
                if not c: break
        except: pass
        s.close(); print('req done OK')
    except Exception as e:
        print('req EXC',e)
def wstat(pids):
    for pid in pids:
        try:
            st=open('/proc/'+pid+'/stat').read().split(')')[1]
            f=st.split()
            print(' ',pid,'state',f[0],'utime',f[11],'kstime',f[12])
        except Exception as e:
            print(' ',pid,e)
pids=['1337','1418','4067','18597','1411','12667']
print('before:'); wstat(pids)
t=threading.Thread(target=req); t.start()
for i in range(3):
    time.sleep(0.5); print('during:'); wstat(pids)
t.join()
time.sleep(1); print('after:'); wstat(pids)
print('=== apache.conf full ===')
print(open('/etc/php-fpm.d/apache.conf').read())
