gpt4 book ai didi

c - 如何从 execl 命令中捕获输出

转载 作者:IT王子 更新时间:2023-10-29 00:53:50 24 4
gpt4 key购买 nike

我正在使用 execl 函数从 C 运行 Linux 进程。当我这样做时,例如:

int cmd_quem() { 
int result;
result = fork();
if(result < 0) {
exit(-1);
}

if (result == 0) {
execl("/usr/bin/who", "who", NULL);
sleep(4); //checking if father is being polite
exit(1);
}
else {
// father's time
wait();
}

return 0;
}

我在控制台上得到了在终端上执行“who”的结果。我想知道的是是否有任何功能可以“捕获”命令的输出结果。我的意思是,如果有办法捕获这个:

feuplive tty5         2009-11-21 18:20

这是 who 命令产生的行之一。

最佳答案

为此,您需要打开一个管道。然后用管道的写入端替换 child 的标准输出,并从父管道的读取端读取。喜欢你的代码的这个修改版本:

int cmd_quem(void) {
int result;
int pipefd[2];
FILE *cmd_output;
char buf[1024];
int status;

result = pipe(pipefd);
if (result < 0) {
perror("pipe");
exit(-1);
}

result = fork();
if(result < 0) {
exit(-1);
}

if (result == 0) {
dup2(pipefd[1], STDOUT_FILENO); /* Duplicate writing end to stdout */
close(pipefd[0]);
close(pipefd[1]);

execl("/usr/bin/who", "who", NULL);
_exit(1);
}

/* Parent process */
close(pipefd[1]); /* Close writing end of pipe */

cmd_output = fdopen(pipefd[0], "r");

if (fgets(buf, sizeof buf, cmd_output)) {
printf("Data from who command: %s\n", buf);
} else {
printf("No data received.\n");
}

wait(&status);
printf("Child exit status = %d\n", status);

return 0;
}

关于c - 如何从 execl 命令中捕获输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1776632/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com