进程的交互
? ?Bionic能夠使原生的應(yīng)用程序來開始和其他的原生進程交互。原生的代碼能夠執(zhí)行shell命令;它能夠在后臺執(zhí)行一個進程和并和它通信。這部分簡要提到一下核心函數(shù):
? ?執(zhí)行一個Shell命令:
? ?這個系統(tǒng)函數(shù)能偶被用來傳遞一個命令到這個shell。為了使用這個函數(shù),這個stdlib.h頭文件應(yīng)該被首先加入:
#include<stdlib.h>
如下,這個函數(shù)阻塞原生代碼直到這命令完成執(zhí)行。
??int result;
= system("mkdir /data/data/com.example.hellojni/temp");
{
/* Execution of the shell failed. */
在某些情況下,擁有一個通信的中轉(zhuǎn)站在原生代碼和執(zhí)行的進程間是需要的。
?這個popen函數(shù)能夠被用來打開一個雙向的管道在父進程和孩子進程之間。為了使用這個函數(shù),這個stdio.h標(biāo)準(zhǔn)的頭文件應(yīng)該被包括。
? FILE* popen(const char* command,const char*type);
? 這個popen函數(shù)的參數(shù)為要執(zhí)行的命令和請求通信的方式和返回一個流指針。錯誤發(fā)生情況下,它將返回NULL。如下,這I/0函數(shù)的流能夠被用來和孩子進程通信通過和一個文件交流。
#include <stdio.h>
...
FILE* stream;
/* Opening a read-only channel to ls command. */
stream = popen("ls", "r");
if (NULL == stream)
{
MY_LOG_ERROR("Unable to execute the command.");
}
else
{
char buffer[1024];
int status;
/* Read each line from command output. */
while (NULL ! = fgets(buffer, 1024, stream))
{
MY_LOG_INFO("read: %s", buffer);
}
/* Close the channel and get the status. */
status = pclose(stream);
MY_LOG_INFO("process exited with status %d", status);
}
當(dāng)孩子進程完成了執(zhí)行,這個流應(yīng)該被關(guān)閉通過pclose函數(shù)。
int pclose(FILE* stream);
它采取流指著作為這個參數(shù)和等待孩子進程來終止和返回這個exit狀態(tài)。
總結(jié)