假设Windows(因为这是此行为流行的唯一平台):
CreatePipe()用于创建通信所需的管道,CreateProcess用于创建子进程.
HANDLE StdInHandles[2];
HANDLE StdOutHandles[2];
HANDLE StdErrHandles[2];
CreatePipe(&StdInHandles[0], &StdInHandles[1], NULL, 4096);
CreatePipe(&StdOutHandles[0], &StdOutHandles[1], NULL, 4096);
CreatePipe(&StdErrHandles[0], &StdErrHandles[1], NULL, 4096);
STARTUPINFO si; memset(&si, 0, sizeof(si)); /* zero out */
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdInput = StdInHandles[0]; /* read handle */
si.hStdOutput = StdOutHandles[1]; /* write handle */
si.hStdError = StdErrHandles[1]; /* write handle */
/* fix other stuff in si */
PROCESS_INFORMATION pi;
/* fix stuff in pi */
CreateProcess(AppName, commandline, SECURITY_ATTRIBUTES, SECURITY_ATTRIBUTES, FALSE, CREATE_NO_WINDOW |DETACHED_PROCESS, lpEnvironment, lpCurrentDirectory, &si, &pi);
Run Code Online (Sandbox Code Playgroud)
这不仅仅是让你顺利完成你想要完成的任务.
对于 POSIX,它应该是这样的:
//Create the pipe.
int lsOutPipe[2];
pipe(lsOutPipe);
//Fork to two processes.
pid_t lsPid=fork();
//Check if I'm the child or parent.
if ( 0 == lsPid )
{//I'm the child.
//Close the read end of the pipe.
close(lsOutPipe[0]);
//Make the pipe be my stdout.
dup2(lsOutPipe[1],STDOUT_FILENO);
//Replace my self with ls (using one of the exec() functions):
exec("ls"....);//This never returns.
} // if
//I'm the parent.
//Close the read side of the pipe.
close(lsOutPipe[1]);
//Read stuff from ls:
char buffer[1024];
int bytesRead;
do
{
bytesRead = read(emacsInPipe[0], buffer, 1024);
// Do something with the read information.
if (bytesRead > 0) printf(buffer, bytesRead);
} while (bytesRead > 0);
Run Code Online (Sandbox Code Playgroud)
您当然应该检查返回值等......