【问题标题】:Program stuck on read() using Pipe() in c在 c 中使用 Pipe() 卡在 read() 上的程序
【发布时间】:2020-05-28 19:59:45
【问题描述】:

我的代码如下: 我在 c 语言中使用管道系统调用。这里我的程序卡在read(the_pipe_1[0],recieved,20); 行前: printf("DUCKKKKKK\n");

输出是:

In parent 
Enter the value
In Child

代码:

#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;
}

【问题讨论】:

  • 它没有卡住,你调用gets 接收来自标准输入的输入,只要你不输入一些输入你的程序就会卡住。还可以考虑使用fgets 而不是gets
  • 你应该检查你的编译器版本/编译器选项 - 由于几个错误,这段代码不应该编译
  • @HarianjaLundu 我提供了输入,但输入后卡住了
  • @Odysseus 我正在使用 gcc 最新版本
  • @AbdullahSultan 使用 gcc-7.4.0 (ubuntu-18-04.1) 不会编译您的代码,因为使用了 gets() 和 2 个无效转换:write(the_pipe_1[1],(char) input,20);write(the_pipe_2[1],(char)palchid,10); – Odysseus 13 分钟前

标签: c ubuntu pipe fork system-calls


【解决方案1】:

简单。将行更改为:

write(the_pipe_1[1], input, 20);

而且效果很好。

说明: 当您将输入(通常是 32 位指针)转换为 char(8 位)时,您创建了一个指向非法地址的指针。在某些访问中,这会导致分段错误。例如,您可以尝试:

//segmentation fault
printf("input - %s\n", (char)input);

但是对于 write(),它的工作方式不同(没有深入研究原因),这导致程序卡住了

PS。 这一行永远不会是真的:

if(pal == "0")

【讨论】:

  • 工作得很好,请您解释一下这个问题!
  • 根本不需要强制转换:write(the_pipe_1[1], input, 20)
  • 我刚刚删除了类型转换并且它正在工作。在它不起作用之前。但是现在是,我的系统是怎么回事?
猜你喜欢
  • 1970-01-01
  • 2020-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-05
  • 2022-12-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多