gpt4 book ai didi

c - fork 三个子进程会产生奇怪的随机输出

转载 作者:太空宇宙 更新时间:2023-11-04 07:37:09 25 4
gpt4 key购买 nike

我尝试让三个进程相互连接。然而,我真的对 fork 第三个过程感到困惑。 fork 和管道只有两个进程可以正常工作。当我添加 +1 循环来测试第三个进程是否生成时,我在终端中得到了奇怪的结果。

这是我的代码(结果很奇怪):

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

int main(){

int status, i;
int pip[2];


/* Spawn 3 subprocesses and pipe the first 2*/
for (i=0; i<3; i++){

if (i==0) pipe(pip);

if (fork()==0){

/* First subprocess */
if (i==0){
dup2(pip[1], 1); //pip[0] will replace stdout
close(pip[0]);
if (execlp("ls", "ls", NULL)) perror("process1");
}

/* Second subprocess */
if (i==1){
dup2(pip[0], 0); //pip[1] -> will replace stdin
close(pip[1]);
if (execlp("more", "more", NULL)) perror("process2");
}

/* Third subprocess */
if (i==2){
close(pip[0]); //reseting fd
close(pip[1]); //reseting fd
open(0); //reseting fd
open(1); //reseting fd
if (execlp("ls", "ls", NULL)) perror("process3");
}


}
}

wait(&status);
return 0;
}

将 for 循环从 3 次改为 2 次循环会停止奇怪的行为。奇怪的是,我会随机在终端中获得以下输出之一:

manos@megistanas:~/Desktop/test$ ./test
test test2.c test3.c test4.c test.5c test.c
test
test2.c
test3.c
test4.c
test.5c
test.c
manos@megistanas:~/Desktop/test$

在那种情况下它正常工作。现在在某些时候它是这样的:

manos@megistanas:~/Desktop/test$ test
test2.c
test3.c
test4.c
test.5c
test.c
test test2.c test3.c test4.c test.5c test.c
manos@megistanas:~/Desktop/test$ manos@megistanas:~/Desktop/test$ manos@megistanas:~/Desktop/test$ manos@megistanas:~/Desktop/test$ manos@megistanas:~/Desktop/test$

在按下回车键的地方,只会写入提示并等待更多输入。第三个奇怪的行为是这样的:

manos@megistanas:~/Desktop/test$ test
test2.c
test3.c
test4.c
test.5c
test.c
(blinking prompt symbol)

一旦我点击回车,程序就会正常结束。有人可以解释发生了什么吗?

最佳答案

open(0);

open(1);

请阅读man page对于打开(2)。

提示:它不需要一个参数。您可能应该使用 -Wall 进行构建,并注意编译器警告。

这可能无法完全解释您所看到的,但鉴于这个明显的错误,我懒得再看下去了。

关于c - fork 三个子进程会产生奇怪的随机输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7863594/

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