进程的交互

来源:互联网 发布:南宁云宝宝大数据 编辑:程序博客网 时间:2024/06/05 05:30

   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状态。

0 0
原创粉丝点击