想要将 stdin 重定向到 execve() 中的文件。所以程序应该像这样执行,我的意思是这就是我在 shell 中执行它的方式并且它的工作原理:
/opt/prog < in.txt
Run Code Online (Sandbox Code Playgroud)
下面是我写的代码,但它似乎不起作用。in.txt 是二进制文件,我想将其重定向到执行程序中的标准输入。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main(void)
{
int fd[2];
pid_t pid;
FILE *f = fopen("in.txt", "rb");
if (pipe(fd) < 0)
return EXIT_FAILURE;
if ((pid = fork()) < 0)
return EXIT_FAILURE;
else if (pid != 0) { /* father */
close(fd[1]);
dup2(fd[0], STDIN_FILENO);
execlp("/opt/prog", "prog", (char *)0);
printf("done\n");
} else { /* son */
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET);
char *string = malloc(fsize + 1);
fread(string, fsize, 1, f);
fclose(f);
close(fd[0]);
write(fd[1], string, 11);
}
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
更新1:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main(void)
{
int fd[2];
pid_t pid;
FILE *f = fopen("in.txt", "rb");
if (pipe(fd) < 0)
return EXIT_FAILURE;
if ((pid = fork()) < 0)
return EXIT_FAILURE;
else if (pid != 0) { /* father */
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET);
char *string = malloc(fsize + 1);
fread(string, fsize, 1, f);
fclose(f);
close(fd[0]);
write(fd[1], string, 11);
} else { /* son */
close(fd[1]);
dup2(fd[0], STDIN_FILENO);
execlp("/opt/prog", "prog", (char *)0);
printf("done\n");
}
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
pipe如果您只想让进程从文件中读取,则不需要:只需dup2读取文件描述符即可STDIN_FILENO。另外,您也希望父母execlp这样做,否则当您的孩子退出时,情况会变得意外......progSIGCHLD
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
int main(void)
{
pid_t pid;
int fd;
fd = open("in.txt", O_RDONLY);
if (fd < 0) {
perror("open");
return EXIT_FAILURE;
}
if ((pid = fork()) < 0) {
perror("fork");
return EXIT_FAILURE;
} else if (! pid) { /* child */
dup2(fd, STDIN_FILENO);
close(fd);
execlp("/opt/prog", "prog", (char *)0);
perror("exec");
return EXIT_FAILURE;
} else { /* parent */
close(fd);
printf("Parent waiting\n");
getchar();
}
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)