|
发表于 2023-11-13 19:34:43
|
显示全部楼层
- 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
- obase=16; 1234
- 4D2
- sh-5.2$
复制代码 |
|