进程的交互
? ?Bionic能夠使原生的應用程序來開始和其他的原生進程交互。原生的代碼能夠執行shell命令;它能夠在后臺執行一個進程和并和它通信。這部分簡要提到一下核心函數:
? ?執行一個Shell命令:
? ?這個系統函數能偶被用來傳遞一個命令到這個shell。為了使用這個函數,這個stdlib.h頭文件應該被首先加入:
#include<stdlib.h>
如下,這個函數阻塞原生代碼直到這命令完成執行。
??int result;
= system("mkdir /data/data/com.example.hellojni/temp");
{
/* Execution of the shell failed. */
在某些情況下,擁有一個通信的中轉站在原生代碼和執行的進程間是需要的。
?這個popen函數能夠被用來打開一個雙向的管道在父進程和孩子進程之間。為了使用這個函數,這個stdio.h標準的頭文件應該被包括。
? FILE* popen(const char* command,const char*type);
? 這個popen函數的參數為要執行的命令和請求通信的方式和返回一個流指針。錯誤發生情況下,它將返回NULL。如下,這I/0函數的流能夠被用來和孩子進程通信通過和一個文件交流。
#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);
}
當孩子進程完成了執行,這個流應該被關閉通過pclose函數。
int pclose(FILE* stream);
它采取流指著作為這個參數和等待孩子進程來終止和返回這個exit狀態。
總結