首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >分叉三个子进程提供奇怪的随机输出。

分叉三个子进程提供奇怪的随机输出。
EN

Stack Overflow用户
提问于 2011-10-23 00:41:16
回答 1查看 119关注 0票数 0

我试着做三个过程来互相管道。然而,我真的对第三个过程感到困惑。分叉和管道--只有两个进程--没有问题。当我添加+1循环来测试第三个进程是否产生时,我在终端中得到了奇怪的结果。

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

代码语言:javascript
复制
#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循环改为2循环而不是3循环停止了奇怪的行为。奇怪的是,随机地,我会在终端中得到其中一个输出:

代码语言:javascript
复制
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$

在这种情况下,它正常工作。在某些情况下,情况是这样的:

代码语言:javascript
复制
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$

点击回车时,只写提示符,等待更多的输入。第三个奇怪的行为是:

代码语言:javascript
复制
manos@megistanas:~/Desktop/test$ test
test2.c
test3.c
test4.c
test.5c
test.c
(blinking prompt symbol)

一旦我点击enter程序就正常结束了。有人能解释一下发生了什么吗?

EN

回答 1

Stack Overflow用户

发布于 2011-10-23 01:07:26

开放(0); 开放(1);

请阅读手册页以打开(2)。

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

这可能并不能完全解释你看到了什么,但是考虑到这个明显的错误,我太懒了,再也看不下去了。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7863594

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档