gpt4 book ai didi

子进程的 printf 未显示在父进程的控制台中

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:24:12 25 4
gpt4 key购买 nike

我有以下代码:

#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

// child process is forked.
// the child executes "ls -al"
// the parent process "waits" for the child and collects it

int main(void) {

char *args[3];
pid_t pid;

printf("i am a parrent and my pid=%d\n",getpid());
if ((pid = fork()) < 0)
fprintf(stderr, "fork error");
else if (pid == 0) {
/* child */
printf("i am a child and my pid=%d",getpid());
args[0] = strdup("ls");
args[1] = strdup("-al");
args[2] = NULL;
if (execvp(args[0], args) < 0)
fprintf(stderr, "exec error");
}
printf("my child got pid=%d\n",pid);
/* parent */
if (waitpid(pid, NULL, 0) < 0)
fprintf(stderr, "waitpid error");
exit(0);
}

这导致了这个输出:

i am a parrent and my pid=11745 
my child got pid=11750
total 144
drwxr--r-- 3 student student 4096 Jun 25 21:18 .
drwxrwxr-x 4 student student 4096 May 24 17:18 ..

一些其他文件...

我的问题是:为什么 child 的 printf ("i am a child...") 输出没有显示在控制台中,而 ls 的输出是?我应该怎么做才能在与父进程相同的控制台上显示它?

最佳答案

首先,您需要在 fork 之前使用 fflush(stdout);,否则您可能会得到以下输出printf("i am a parrent and my pid=%d\n",getpid()); 在你是 parent 和你 child 的标准输出缓冲区中。然后你需要一个 fflush(stdout)fcloseall()exec 调用之前,因为一个 exec 完全浪费你的旧过程镜像和你的输出缓冲区。

或者,您可以切换到行缓冲或将其关闭。

在处理 exec 错误时,除了打印错误之外,您还应该 _exit ,否则它会继续沿着它的父级路径。

关于子进程的 printf 未显示在父进程的控制台中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38031664/

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