所以我试图让程序将信息从一个进程传递到另一个进程。它应该从 child 开始并减去 5 然后转到 parent 并除以 5。我似乎遇到的问题是输出出现在 parent 具有正确值但 child 没有正确值的地方并且它来了以某种奇怪的顺序出来。
预期输出:
x = 19530
迭代 1
child :x = 19525
父级:x = 3905
迭代 2
child :x = 3900
父级:x = 780
迭代 3
child :x = 775
parent :x = 155
迭代 4
child :x = 150
parent :x = 30
迭代 5
child :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;
我得到的输出:
child :x = 19525
child :x = 19520
child :x = 19515
child :x = 19510
child :x = 19505
父级:x = 3905
父级:x = 780
parent :x = 155
parent :x = 30
父级:x = 5
不太确定我哪里出错了。 parent 给出了正确的值(value),但 child 却没有。并且不确定如何让它们以正确的顺序打印。
最佳答案
您需要使用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;
}
关于c - 使用管道在进程之间交换信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42893640/