gpt4 book ai didi

c - fork 后将父进程保持在前台

转载 作者:太空狗 更新时间:2023-10-29 16:07:53 25 4
gpt4 key购买 nike

我有一个 C 程序,它派生了一个子进程,我从 linux shell 运行它。

我的问题是,在 fork 之后,父进程移动到 shell 后台。我希望父进程留在前台。

这是一个简单的例子:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void)
{
int i;
for (i = 0; i < 3; i++) {
printf("Before Fork\n");
sleep(1);
}

printf("forking...\n");
pid_t pid = fork();
if (pid) {
// child
printf("Child started and now exiting\n");
exit(EXIT_SUCCESS);
}

// parent
wait(NULL);
for (i = 0; i < 3; i++) {
printf("After Fork\n");
sleep(1);
}

return 0;
}

输出(稍后添加注释)

Before Fork
Before Fork
Before Fork
forking...
Child started and now exiting
After Fork
gregp@gregp-ubuntu:~/fork_example$ After Fork # <--- User returned to shell
After Fork

请注意,fork 后不久,用户将返回到 shell 提示符,程序继续在后台运行。我不希望这种情况发生。我希望程序继续在前台运行。

期望的输出(稍后添加评论)

Before Fork
Before Fork
Before Fork
forking...
Child started and now exiting
After Fork
After Fork
After Fork
# Program now exits and user returns to shell
gregp@gregp-ubuntu:~/fork_example$

最佳答案

第一个 pid 在父级中返回,所以你的条件应该是

if (!pid)

因为你代码中的child不会去if。那是因为

On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately.

关于c - fork 后将父进程保持在前台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18389692/

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