C 通過匿名管道操作adb shell的輸入輸出

2021-06-27 07:40:29 字數 2557 閱讀 4856

我封裝了乙個類cadbshell,用於方便地來操作adb shell命令,使用方法:

cadbshell shell;

shell.start();

shell.runcmd("su\ncd /data/data\n");

shell.runcmd("cd " + strpackagename + "\nls");

shell.stop();

標頭檔案:

/*

通過管道操作adb shell --by sing

*/#pragma once

#include #include class cadbshell

;

原始檔:

#include "stdafx.h"

#include "adbshell.h"

dword __stdcall threadadbshellproc(void *pvoid)

return 0;

}cadbshell::cadbshell(void)

cadbshell::~cadbshell(void)

//啟動adb shell,如果成功則進入#狀態,可以使用runcmd執行命令

bool cadbshell::start()

if( createpipe(&m_hreadpipe2,&m_hwritepipe2,&sat,null)==false )

startupinfo.cb=sizeof(startupinfo);

getstartupinfo(&startupinfo);

startupinfo.hstderror=m_hwritepipe;

startupinfo.hstdoutput=m_hwritepipe;

startupinfo.hstdinput=m_hreadpipe2;

startupinfo.dwflags=startf_useshowwindow | startf_usestdhandles;

startupinfo.wshowwindow=sw_hide;

if( createprocess(null, "adb.exe shell", null, null, true, 0, null, null, &startupinfo, &pinfo)==false )

closehandle(m_hwritepipe);

closehandle(m_hreadpipe2);

closehandle(pinfo.hthread);

closehandle(pinfo.hprocess);

//m_hprocess = pinfo.hprocess;

dword dwthread = false;

hthread = createthread(null, 0, threadadbshellproc, this, 0, &dwthread);//這個引數你根據你的需要決定要不要

if ( hthread==null )

m_hevent = createevent(null, false, false, null);

return true;

}//這裡輸入的是在adb shell狀態下的批處理命令,如果有多條請以\n分隔

bool cadbshell::runcmd(const cstring&strcmdline)

//先等待執行緒函式準備好

waitforsingleobject(m_hevent, infinite);

while ( true )

stronecmd = strcmdline.mid(npos1, npos2 - npos1).trim();

//命令長度至少為2

if ( stronecmd.getlength() >= 2 )

++npos2;

if ( npos2 >= strcmdline.getlength() )

} return bsuccess;

}//退出shell命令狀態,關閉程序。不能通過terminateprocess方式結束,否則會有讀取不全的情況

bool cadbshell::stop()

//return true;

}//讀取輸出結果,呼叫前請務必呼叫stop先結束

cstring cadbshell::getoutput()

if ( npos1!=-1 )

return m_stroutput;

}bool cadbshell::loop()

; dword dwread = 0;

while( true ) else

} }closehandle(m_hreadpipe);

closehandle(m_hwritepipe2);

closehandle(m_hevent);

m_hevent = null;

closehandle(hthread);

hthread = null;

return true;

}

C 程序通訊之匿名管道

匿名管道只能用來實現同一臺機器上父子程序間通訊,而不能實現跨網路的通訊。利用匿名管道實現父子程序通訊時,需要注意 因為匿名管道沒有名稱,所以只能在父程序中呼叫createprocess函式建立子執行緒時,將管道的讀寫控制代碼傳遞給子執行緒。1.父程序 private handle m hread 匿...

通過匿名管道在程序間雙向通訊

由於匿名管道只能是單向的,因此要建立雙向通訊必須建立2個管道。父程式 view plaincopy to clipboardprint?int main closehandle hreadpipe1 closehandle hreadpipe2 closehandle hwritepipe1 clo...

通過匿名管道獲取CMD命令框輸出內容

以前有個人諮詢我說,要怎麼程式設計實現獲取控制台視窗或者是cmd視窗輸出的資料內容。當時水平有限,很多知識還不是很了解。但是憑藉著有一點基礎,而且之前在網路上瀏覽過相關的技術實現,還有些印象,便回答ta說,可以用匿名管道的方式來實現。管道是一種用於在程序間共享資料的機制,其實質是一段共享記憶體。wi...