等待2个子进程

问题描述 投票:0回答:1

我正在尝试编写一个C程序,其中的主要过程创建了两个子进程:Ping和Pong。 Ping打印“ ping”后跟一个数字,Pong打印“ pong”后跟一个数字,输出必须与图1中运行的示例一样:“

enter image description here

这是我试图做的:

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

void main(){

//initializing pipes
int td[2];
int td2[2];

pipe(td);
pipe(td2);

int pid=fork();
if(pid){ //in parent process

int pid2=fork();

if(pid2){// still in parent process



//1st time
int number1;
printf("Enter a number: ");
scanf("%d",&number1);

write(td[1],&number1,sizeof(number1));
printf("<>");

write(td2[1],&number1,sizeof(number1));
printf("--");


//2nd time
int number2;
printf("Enter a number: ");
scanf("%d",&number2);

write(td[1],&number2,sizeof(number2));
printf("<>");

write(td2[1],&number2,sizeof(number2));
printf("--");

}
else{// in pong process

int number;

read(td2[0],&number,sizeof(number));
printf("pong%d \n",number);

}


}

else{ //in ping process

int number;

read(td[0],&number,sizeof(number));
printf("ping%d \n",number);

}

}//main end

说明:我在这里遇到的问题是,在ping之前先打印pong,并且父进程不等待其子进程结束(并且某些输出在root / desktop等之后打印。)

另一个我解决的问题,我在父进程中有read方法,它解决了我的问题,因为我知道read会迫使程序等到向管道中写入内容,但是在这种情况下,我们在其中写入了父进程,因此父进程不在等待

我也尝试实现wait(NULL),但似乎不起作用。

任何建议将不胜感激

c pipe fork ipc
1个回答
1
投票

[您(您的讲师)似乎太复杂了。

所以,你想让你的main()

int main(void) {
    int n;
    //set up pipes and forks
    printf("Enter a number"); scanf("%d", &n);
    // make child1 output " ping<n>\n"
    puts(" <>");
    // make child2 output " pong<n>\n"
    printf(" --\nEnter a second number"); scanf("%d", &n);
    // make child1 output " ping<n>\n"
    puts(" <>");
    // make child2 output " pong<n>\n"
    puts(" -- THE END --");
    // close pipes
    return 0;
}

因此,除了"ping""pong"(以及使用不同的管道)外,孩子绝对是相同的。也许我们可以发送带有数字的字符串并保持函数数量减少?否...在创建过程时如何设置字符串?听起来更好

// set up pipes and forks
int pipes1[2], pipes2[2];
pipe(pipes1);
if (fork() == 0) /* child #1 */ child("ping", pipes1);
close(pipes1[0]); // the read end of the pipe belongs to the child
pipe(pipes2);
if (fork() == 0) /* child #2 */ child("pong", pipes2);
close(pipes2[0]); // we are not using the read end of the pipe

现在...我们如何生孩子(孩子正在等待他们的read()电话通话)工作?好吧,容易!我们写在管道的末端

scanf("%d", &n); // get value from user
write(pipes1[1], &n, sizeof n); // automatically unblock child1
write(pipes2[1], &n, sizeof n); // automatically unblock child2

为第二个用户输入重复这些语句。

不要忘记关闭管道的写端

close(pipes1[1]);
close(pipes2[1]);

这就是main()函数。孩子的功能呢? child(char *sign, int pipes[2])

void child(char *sign, int pipes[2]) {
    close(pipes[1]); // close write end
    int i;
    for (;;) {
        if (read(pipes[0], &i, sizeof i)) {
            printf(" %s%d\n", sign, i); // print and go back to waiting at the read()
        } else {
            break; // exit the loop when read fails
        }
    }
    close(pipes[0]); // no more reading
    exit(EXIT_SUCCESS); // not going back to main()
}
© www.soinside.com 2019 - 2024. All rights reserved.