|
发表于 2023-11-13 19:15:38
|
显示全部楼层
本楼为最佳答案
本帖最后由 人造人 于 2023-11-13 19:17 编辑
- sh-5.2$ cat main.c
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <sys/wait.h>
- void exec_bc(const char *str) {
- int pipe_fd[2];
- if(pipe(pipe_fd) == -1) { // 创建管道
- perror("pipe");
- exit(EXIT_FAILURE);
- }
- pid_t pid = fork();
- if(pid == -1) {
- perror("fork");
- exit(EXIT_FAILURE);
- } else if(pid == 0) { // 子进程
- if(dup2(pipe_fd[0], STDIN_FILENO) == -1) { // 将管道输入重定向到标准输入
- perror("dup2");
- exit(EXIT_FAILURE);
- }
- close(pipe_fd[0]);
- close(pipe_fd[1]);
- execlp("bc", "bc", NULL); // 调用bc程序
- // 如果execlp函数执行失败,输出错误信息并直接退出程序。
- perror("execlp failed");
- exit(EXIT_FAILURE);
- } else { // 父进程
- write(pipe_fd[1], str, strlen(str)); // 将str写入管道
- close(pipe_fd[0]);
- close(pipe_fd[1]);
- // 不需要获取子进程的退出状态,直接使用NULL即可。
- waitpid(pid, NULL, 0);
- }
- }
- int main() {
- char buff[1024];
- fgets(buff, 1024, stdin);
- exec_bc(buff);
- return 0;
- }
- sh-5.2$ ./main
- 1+2+3
- 6
- sh-5.2$ ./main
- 2^32
- 4294967296
- sh-5.2$ ./main
- obase=2; 123
- 1111011
- sh-5.2$ ./main
- for(i = 0; i < 10; ++i) {print i + 1, "\n"}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- sh-5.2$
复制代码 |
|