[英]Program stuck on read() using Pipe() in c
My code is as follows: I am using pipe system call in c language.我的代码如下: 我在 c 语言中使用管道系统调用。 Here my program is stuck on read(the_pipe_1[0],recieved,20);
这里我的程序卡在read(the_pipe_1[0],recieved,20);
before line: printf("DUCKKKKKK\\n");
行前: printf("DUCKKKKKK\\n");
The output is :输出是:
In parent
Enter the value
In Child
The code:编码:
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include<sys/wait.h>
int isPalindrome(char str[]);
int main(int argc, char const *argv[]) {
int the_pipe_1[2];
int the_pipe_2[2];
char recieved[20];
char input[20];
char pal[10];
int palchid;
int pipeVal = pipe(the_pipe_1);
if (pipeVal == -1 ) {
printf("Pipe 1 failed\n");
}
if (pipe(the_pipe_2) == -1 ) {
printf("Pipe 2 failed\n");
}
int forkVal = fork();
if (forkVal > 0) {
printf("In parent \n");
close(the_pipe_1[0]);
printf("Enter the value\n");
gets(input);
write(the_pipe_1[1],(char) input,20);
wait(NULL);
close(the_pipe_2[1]);
read(the_pipe_2[0],pal,10);
if(pal == "0")
{
printf("Not plaindrome\n");
}
else
printf("Plaindrome\n");
}
else if(forkVal == 0)
{
printf("In Child\n");
close(the_pipe_1[1]);
read(the_pipe_1[0],recieved,20);
printf("DUCKKKKKK\n");
printf("Val of recieved %s \n",&recieved );
palchid = isPalindrome(recieved);
close(the_pipe_2[0]);
write(the_pipe_2[1],(char)palchid,10);
}
return 0;
}
int isPalindrome(char str[])
{
int l = 0;
int h = strlen(str) - 1;
while (h > l)
{
if (str[l++] != str[h--])
{
return 0;
}
}
return 1;
}
simple.简单的。 change the line to:将行更改为:
write(the_pipe_1[1], input, 20);
and it works fine.它工作正常。
Explanation: When you cast input(which is usually a 32bit pointer) to char(which is 8 bit) you created a pointer to an illegal address.说明:当您将输入(通常是 32 位指针)转换为 char(8 位)时,您创建了一个指向非法地址的指针。 On some accesses, this would cause segmentation fault.在某些访问中,这会导致分段错误。 For instance, you can try:例如,您可以尝试:
//segmentation fault
printf("input - %s\n", (char)input);
but for write(), which works differently(didn't delve into why), this caused the program to get stuck instead但是对于 write(),它的工作方式不同(没有深入研究原因),这导致程序卡住了
PS.附注。 this row will never be true:这一行永远不会是真的:
if(pal == "0")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.