【发布时间】: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