我有这个 linux 程序,它使用管道将数据从父级传输到子级,并根据返回值给出答案;
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
int fd[2], nbytes;
pid_t childpid;
char readbuffer[80];
int log_variable;
char login[]="login";
void toLower(char str[]){//converts UPPERCASE to lowercase
int i;
for(i=0; i<strlen(str); i++)
str[i]=tolower(str[i]);
}
//end of toLower
int compareStrings(char str1[], char str2[]){//compares 2 strings
if(strlen(str1) == strlen(str2))
{
int i;
for( i=0; i<strlen(str1); i++){
if(str1[i] != str2[i])
return 0;
return 1;
}
}
else return 0;
}
int loginCommand(char argument[]){//test function so far for login, myfind etc
int fileDescr;
pipe(fd);//defines the pipe
switch(childpid=fork()){//switch statement to control parent and child
case -1:
perror("fork -1\n");
exit(0);
case 0://child
close (fd[1]);
char givenUsername[20];
//open the config file and copy the username from it, assign to a variable, and then
//compare it to readbuffer
int nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
if(strcmp(readbuffer, login) == 0){
printf("1: ");
return 1;
}
else {
printf("0: ");
return 0;
}
exit(0);
default:
//parent
close(fd[0]);
write(fd[1], argument, sizeof(argument));
wait(NULL)!=-1;
exit(0);
}
}
main(){
char input[20];
int logs;
while(logs == 0){
printf("Insert command: \n");
scanf("%s", input);
toLower(input);
logs=(loginCommand(input));
if(logs == 1) {printf("System accessed\n"); }
if(logs == 0) {printf("This username doesnt exist\n"); }
}
return 0;
}
但我最大的问题是我输入了“login”的值,这与上面的登录变量相同,程序正确响应,但是如果我将该变量更改为“loginloginlogin”的值,假设,并且如果我从控制台输入相同的值,程序会说该值不正确。我的假设是程序不会从控制台读取整个输入,但我已经更改了字符串的大小,并且仍然具有相同的行为。
谁能知道这是怎么回事?
最佳答案
问题出在这里:
write(fd[1], argument, sizeof(argument));
当您将数组传递给函数时,它会衰减为指向第一个字符的指针。对指针执行 sizeof
会得到指针的大小,而不是指针指向的大小。
要获得字符串的长度,您需要使用 strlen
.
哦,不要忘记使用 strlen(argument) + 1
来发送字符串终止符(或者在子进程中终止字符串)。
关于c - Linux 管道不良行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33363698/