在不更改stdin上的缓冲的情况下执行fork-then-execve的方法是使用文件描述符重定向。具体步骤如下:
下面是一个示例代码:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main() {
int pipefd[2];
pid_t pid;
// 创建管道
if (pipe(pipefd) == -1) {
perror("pipe");
return 1;
}
// 创建子进程
pid = fork();
if (pid == -1) {
perror("fork");
return 1;
}
if (pid == 0) {
// 子进程中
close(pipefd[1]); // 关闭写入端的文件描述符
dup2(pipefd[0], 0); // 将读取端的文件描述符复制到stdin
close(pipefd[0]); // 关闭读取端的文件描述符
// 执行命令
char *args[] = {"/bin/sh", "-c", "command", NULL};
execve(args[0], args, NULL);
perror("execve");
return 1;
} else {
// 父进程中
close(pipefd[0]); // 关闭读取端的文件描述符
// 写入命令
char *command = "command\n";
write(pipefd[1], command, strlen(command));
close(pipefd[1]); // 关闭写入端的文件描述符
// 等待子进程结束
wait(NULL);
}
return 0;
}
这样,就可以在不更改stdin上的缓冲的情况下执行fork-then-execve。
领取专属 10元无门槛券
手把手带您无忧上云