这里在 Linux 中具有"CreatePipe"和"CreateProcessW"功能吗?

Is here has "CreatePipe" and "CreateProcessW" function in Linux?

本文关键字:CreateProcessW 功能 CreatePipe 这里 Linux      更新时间:2023-10-16

如何在Linux中使用"CreatePipe"answers"CreateProcessW"的函数,当我在Linux中编译C++代码时,会出现以下错误:"CreatePipe'未在此范围内声明。"CreateProcessW"未在此作用域中声明。

Posix/Linux:

int pipe(int pipefd[2]);

pipefd[0]表示管道的读取端
pipefd[1]表示管道的写入端。

Linux特定:

int pipe2(int pipefd[2], int flags);

对于CreateProcess,Posix/Linux版本只需几个步骤即可完成。

  • 调用fork()创建一个新进程-仍然运行同一程序-因此两个进程现在将从调用fork()的同一点继续运行同一个程序。通过检查fork()的返回值(进程id(来确定它是父进程还是子进程
  • duppipe使用int dup2(int oldfd, int newfd);为新进程替换stdinstdout返回的文件描述符
  • 使用exec*函数之一在新进程中执行程序。

    // create pipes here
    if(pid_t pid = fork(); pid == -1) {
    // fork failed
    } else if(pid == 0) { // child process goes here (with a new process id)
    // dup2(...)
    // exec*()
    } else {              // parent process goes here
    // do parenting stuff
    }
    

示例:

#include <unistd.h>
#include <sys/types.h>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <stdexcept>
struct Pipe {
Pipe() {
if(pipe(io)) throw std::runtime_error("pipe failure");
}
~Pipe() {
close_rd();
close_wr();
}
void close_rd() { closer(io[0]); }
void close_wr() { closer(io[1]); }
int rd() { return io[0]; }
int wr() { return io[1]; }
private:
void closer(int& fd) {
if(fd != -1) {
close(fd);
fd = -1;
}
}
int io[2];
};
int main() {
Pipe parent_write, parent_read;
if(pid_t pid = fork(); pid == -1) {
// fork failed
return 1;
} else if(pid == 0) {   // child process goes here (with a new process id)
// close file descriptors we don't need:
parent_write.close_wr();
parent_read.close_rd();
// duplicate into the place where stdin/stdout was
dup2(parent_write.rd(), fileno(stdin));
dup2(parent_read.wr(), fileno(stdout));
// execute a program
execl("/bin/ls", "/bin/ls", nullptr);
// exec* functions never returns if successful, so if we get here, it failed:
std::exit(1);
} else {               // parent process goes here
std::cout << "child process " << pid << " startedn";
}
// close file descriptors we don't need:
parent_write.close_rd();
parent_read.close_wr();
// read data from child process using the file descriptor in parent_read.rd()
char buf[1024];
ssize_t rv;
while((rv = read(parent_read.rd(), buf, 1024))) {
write(fileno(stdout), buf, static_cast<size_t>(rv));
}
// use write(parent_write.wr(), ...) to write to the child.
}