所以我试图让程序将信息从一个进程传递到另一个进程。它应该从孩子开始并减去5然后去父母并除以5.我看似有的问题是输出出现在父母有正确价值但孩子没有并且它来了的地方出于某种奇怪的顺序。
预期产出:
x = 19530
ITERATION 1
孩子:x = 19525
父:x = 3905
ITERATION 2
孩子:x = 3900
父:x = 780
ITERATION 3
孩子:x = 775
父:x = 155
ITERATION 4
孩子:x = 150
父:x = 30
ITERATION 5
孩子:x = 25
家长:x = 5
这是我的代码:
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int x = 19530;
pid_t childpid;
int child[2], parent[2];
int i, j;
if (pipe(parent) == -1 || pipe(child) == -1)
{
perror("failed to pipe");
exit(-1);
}
if ((childpid = fork()) <= -1)
{
perror("failed to fork");
exit(-1);
}
if (childpid == 0)
{
//close(parent[1]);
//close(child[0]);
for (j = 0; j < 5; j++)
{
x -= 5;
if (write(child[1], &x, sizeof(x)) <= 0)
{
perror("Child: failed to write to the pipe");
exit(-1);
}
printf("Child : x = %d\n", x);
}
//close(parent[0]);
//close(child[1]);
exit(-1);
}
else
{
//close(parent[0]);
//close(child[1]);
for (i = 0; i < 5; i++)
{
sleep(1);
x /= 5;
x -= 1;
if (write(parent[1], &x, sizeof(x)) <= 0)
{
perror("parent: failed");
exit(-1);
}
printf("Parent : x = %d\n", x);
}
//close(parent[1]);
//close(child[0]);
exit(-1);
}
return 0;
}
我得到的输出:
孩子:x = 19525
孩子:x = 19520
孩子:x = 19515
孩子:x = 19510
孩子:x = 19505
父:x = 3905
父:x = 780
父:x = 155
父:x = 30
家长:x = 5
不确定我哪里出错了。父母给出了正确的价值,但孩子却没有。并且不确定如何让它们以正确的顺序打印。
答案 0 :(得分:1)
您需要使用read
从其他进程获取更新的值。
以下是每次迭代中发生的事情:
Child:
1. read x from parent pipe
2. x = x - 5
3. write x to child pipe
Parent:
1. write x to the parent pipe
2. read x from child pipe
3. x = x / 5
下面的代码提供了正确的输出:
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
int main() {
int x = 19530;
pid_t childpid;
int child[2], parent[2];
int i, j;
if (pipe(parent) == -1 || pipe(child) == -1) {
perror("failed to pipe");
exit(-1);
}
if ((childpid = fork()) <= -1) {
perror("failed to fork");
exit(-1);
}
if (childpid == 0){ // child
close(parent[1]);
close(child[0]);
}else { // parent
close(parent[0]);
close(child[1]);
}
for (int i = 0; i < 5; i ++){
if (childpid == 0) { // child
sleep(1);
printf("ITERATION %d\n", i+1);
// 1. read
if (read(parent[0], &x, sizeof(x)) <= 0) {
perror("Child: failed to read from the pipe");
exit(-1);
}
// 2. subtract
x -= 5;
// 3. write
if (write(child[1], &x, sizeof(x)) <= 0) {
perror("Child: failed to write to the pipe");
exit(-1);
}
printf("Child : x = %d\n", x);
} else {
// 1. write
if (write(parent[1], &x, sizeof(x)) <= 0) {
perror("parent: failed");
exit(-1);
}
// 2. read
if (read(child[0], &x, sizeof(x)) <= 0) {
perror("Parent: failed to read from the pipe");
exit(-1);
}
// 3. divide
x /= 5;
printf("Parent : x = %d\n", x);
}
}
return 0;
}