out*_*der 4 c linux subprocess
我正在使用该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;
}
Run Code Online (Sandbox Code Playgroud)
我在控制台上得到了在终端上做"谁"的结果.我想知道的是,是否有任何函数可以"捕获"命令的输出结果.我的意思是,如果无论如何都要抓住这个:
feuplive tty5 2009-11-21 18:20
Run Code Online (Sandbox Code Playgroud)
哪个是who命令产生的行之一.
首先,execl除非出现像找不到可执行文件的问题,否则不会返回.这sleep(4)可能永远不会执行.
至于重定向和获取输出,请查看Unix Programming FAQ.寻找spawn_background_command.
为此,您需要打开一个管道。然后用管道的写入端替换子级的标准输出,并从父级管道的读取端读取。就像你的代码的这个修改版本:
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;
}
Run Code Online (Sandbox Code Playgroud)