c - C 父子通讯增加打印计数器
问题描述
我正在尝试编写一个程序,以便父进程和子进程可以相互通信。父进程和子进程应该打印从 1 到 100 的值,其中每个进程打印的值每次增加 1。现在我面临的问题是,我对管道一无所知。我从在线阅读材料中收集到的是,我可以使用管道来读取和写入值。我利用它在子进程中打印一些东西,并将一些东西发回给父进程。现在,我不确定如何让父母在为自己打印后返回给孩子?我知道我的代码可能全错了,但我真的不确定我应该做什么。
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc, const char * argv[]) {
int fd[2];
if (pipe(fd)== -1){
printf("An error occured while opening the pipe\n");
}
int id = fork();
int i = 0;
if (id == 0){
close(fd[0]);
printf("In child: %d", i);
i ++;
write(fd[1], &i, sizeof(int));
close(fd[1]);
} else {
wait(NULL);
close(fd[1]);
int y;
read(fd[0],&y, sizeof(int));
close(fd[0]);
}
}
解决方案
为简单起见,检查返回值和处理错误由您决定。这只会在两者之间进行0 - 9
,您将不得不扩展数学。
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{
int pipefd_1[2];
int pipefd_2[2];
pid_t cpid;
pipe(pipefd_1);
pipe(pipefd_2);
cpid = fork();
if (cpid == 0) { /* Child reads from pipe 1, writes to pipe 2*/
char cval[] = {'0'};
close(pipefd_1[1]); /* Close unused write and read ends */
close(pipefd_2[0]);
while (atoi(cval) != 9) {
read(pipefd_1[0], cval, 1);
printf("Child print %d\n", atoi(cval));
cval[0] += 1;
write(pipefd_2[1], cval, 1);
}
} else {
char cval[] = {'0'}; /* Parent writes buf to pipe 1 */
close(pipefd_1[0]); /* Close unused read end */
close(pipefd_2[1]);
while (atoi(cval) != 9) {
write(pipefd_1[1], cval, 1);
read(pipefd_2[0], cval, 1);
printf("Parent print %d\n", atoi(cval));
cval[0] += 1;
}
}
}
输出
推荐阅读
- mercurial - 尝试从 hg 中提取存储库时出现未知修订错误
- repast-simphony - 为什么 Repast Simphony 在批处理中找不到模型输出?
- spring - Spring cloud circuitbreaker:创建断路器方法创建一个新的断路器而不是返回现有的断路器
- javascript - 获取给定日期时间字符串和日期的日期格式
- java - 泛型转换/实例检查/排除类型参数
- compiler-errors - 有没有办法在 Vala 上使用 libgit2-glib?
- c - MergeSorted 数组在第一个位置有一个额外的零,它仅在对大数组进行测试时显示该错误
- c# - 并非所有属性在 UIAutomation 的 AutomationElement 类的 Visual Studio IntelliSense 中都可见
- rdf - RDF 数据库中的本体和 RDF 数据之间是否存在脱节?
- sql - 将具有 NULL 值的额外列从一个表插入到另一个表 HIVE