从用户中读取整数并写入子管道,然后父管道从中读取
read integer from user and write into child pipe and then parent pipe read from it
我正在尝试在管道中做简单的读/写但是它给了我错误
这是我的代码:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#define BUFSIZE 80
int main()
{
int fd[2],n,i,h;
char buf[BUFSIZE];
pipe(fd);
switch(fork())
{
case -1 :printf("Fork Error");
exit(0);
case 0 :close(fd[0]);
printf("Enter N :");
scanf("%d",&n);
write(fd[1],&n,sizeof(n));
close(fd[1]);
case 1 :close(fd[1]);
n=read(fd[0],&h,sizeof(h));
for(i=1;i<=h;i++)
{
if(i%2==1)
{
write(1,&i,n);
}
}
close(fd[0]);
}
exit(0);
}
在这段代码中:子节点的fd[0]指针被关闭并从子节点的fd[1]指针中写入,然后父节点从fd[1]指针中读取并将其存储在h变量中,然后变量i的值进入STDOUT_FILENO(1)并在标准输出
中显示输出输出:kartik@ubuntu: ~/桌面/isp $
输入N:6
6: command not found
这里有几个问题:
- 您在子进程中提示
N
,但是父进程是从终端接收输入的进程。所以当你输入"6"的时候,父进程已经退出了,你正在向shell输入这个值。将printf
和scanf
移动到fork
之前,您应该能够正确读取该值。 - 当
fork()
从父级返回时,您的case 1
将不会被输入,这似乎是您的意图。fork()
将子进程的pid返回给父进程。因为特殊的init
进程的pid是1,所以这永远不会为真。修改case 1:
为default
,以处理父进程。 - 你没有在你的开关箱结束时使用
break
。在C语言中,切换用例"失败",这意味着一旦一个用例的语句完成,它将继续运行下一个用例的语句。每个case末尾的break
语句可以防止这种情况发生。
经过这些修改,你现在有了:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#define BUFSIZE 80
int main()
{
int fd[2],n,i,h;
pid_t pid; // to capture the child pid
char buf[BUFSIZE];
// prompt for N before forking
printf("Enter N :");
scanf("%d",&n);
pipe(fd);
switch((pid=fork())) // saving the child pid in case we want to use it later
{
case -1 :
printf("Fork Error");
exit(0); // no break needed here because of exit
case 0 :
close(fd[0]);
write(fd[1],&n,sizeof(n));
close(fd[1]);
break; // end of case 0
default :
close(fd[1]);
n=read(fd[0],&h,sizeof(h));
printf("h=%dn",h);
for(i=1;i<=h;i++)
{
if(i%2==1)
{
//write(1,&i,n);
printf("%dn",i);
}
}
close(fd[0]);
break; // end of default case
}
exit(0);
}
父进程需要等待它的子主题完成它的工作并将数据推送到管道中…
so add below line.
wait(&status);
相关文章:
- 先进先出:一个进程永远不会从管道读取
- read() 在 select() 阻塞之后,当从生成的进程从管道读取时
- 读取文件挂在管道读取上
- 使用两个不同的管道C 读取和写入相同的过程
- 启动子进程时的争用条件导致从管道读取挂起
- 为什么从管道读取时libc++getline会阻塞,而libstdc++getline不会
- 如何从 GStreamer 管道读取数据中的特定字段
- 命名管道读取超时
- 使用“反引号”而不是管道读取值 |C++
- 从管道读取输入时出现scanf问题
- 从 Linux 中的多个非阻塞命名管道读取
- 父进程没有完全从命名管道读取数据
- 获取错误代码 998 尝试从命名管道读取时对内存位置的访问无效
- 无法从匿名管道读取
- 在dup2()之后使用std::cin从管道读取
- 为什么 ReadFile() 不返回 0 ?程序尝试永远从管道读取数据
- 执行控制台程序,写入标准输入并使用管道读取结果
- 从管道读取随机失败
- 为什么我的程序在管道读取过程中冻结?
- 为什么可以'd '从管道读取比我自己的程序使用ifstream更快