微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何正确使用管道到标准输入和标准输出

如何解决如何正确使用管道到标准输入和标准输出

我正在尝试使用 gcc 在运行时编译汇编代码。我从标准输入(汇编代码获取输入并将结果以二进制格式输出到标准输出。 由于某种原因,我的程序卡住了(我认为是因为它在等待来自 stdin 的输入时阻塞了)。

代码如下:

char* assemble(char* assembly_code){
        

char *binaryPath = "/usr/bin/gcc";
char *binary = "gcc";
char *arg1 = "-x";
char *arg2 = "assembler";
char *arg3 = "-";
char *arg4 = "-o";
char *arg5 = "/dev/stdout";
char *arg6 = "-nostdlib";
char *arg7 = "-Wl,--oformat=binary";
char *arg8 = "-m64";

char data[1024];
memset(data,1024);

pid_t pid = 0;

int pipe_fd_1[2];
int pipe_fd_2[2];

int status;

pipe(pipe_fd_1);
pipe(pipe_fd_2);

pid = fork();

if (pid == 0){

    dup2(pipe_fd_1[0],fileno(stdin));
    dup2(pipe_fd_2[1],fileno(stdout));    

    close(pipe_fd_1[1]);
    close(pipe_fd_2[0]);
    
    execl(binaryPath,binary,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,(char*) NULL);

    close(pipe_fd_1[0]);
    close(pipe_fd_2[1]);

    exit(1);
}
close(pipe_fd_1[0]);
close(pipe_fd_2[1]);

write(pipe_fd_1[1],assembly_code,strlen(assembly_code));
read(pipe_fd_2[0],(void*)data,1024);

close(pipe_fd_1[1]);
close(pipe_fd_2[0]);

printf("Received answer: %s\n",(char*)data);

kill(pid,SIGKILL); 
waitpid(pid,&status,0);

return data;



}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。