簡體   English   中英

在 c 中使用 Pipe() 卡在 read() 上的程序

[英]Program stuck on read() using Pipe() in c

我的代碼如下: 我在 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;
}

簡單的。 將行更改為:

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

它工作正常。

說明:當您將輸入(通常是 32 位指針)轉換為 char(8 位)時,您創建了一個指向非法地址的指針。 在某些訪問中,這會導致分段錯誤。 例如,您可以嘗試:

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

但是對於 write(),它的工作方式不同(沒有深入研究原因),這導致程序卡住了

附注。 這一行永遠不會是真的:

if(pal == "0")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM